package com.itlong.cloud.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.DTO.app.AppElevatorAuthDTO;
import com.itlong.cloud.POJO.DTO.app.AppUploadPassRecordDTO;
import com.itlong.cloud.POJO.DTO.common.IotPubMessageDTO;
import com.itlong.cloud.POJO.DTO.property.*;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.app.*;
import com.itlong.cloud.POJO.VO.operate.OperateUpdateDetailVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppDeviceDao;
import com.itlong.cloud.app.dao.IAppDevicePassRecordDao;
import com.itlong.cloud.app.service.IAppDeviceService;
import com.itlong.cloud.commons.dao.ICloudElevatorDao;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.operate.dao.IOperatePackageDao;
import com.itlong.cloud.property.dao.*;
import com.itlong.cloud.property.service.ICloudIntercomService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <desc>
 *      云对讲设备管理服务接口实现
 * </desc>
 *
 * @createDate 2017-11-15.
 */
@Service
@RefreshScope
public class CloudIntercomServiceImpl implements ICloudIntercomService{
    private static final Logger LOG = LoggerFactory.getLogger(CloudIntercomServiceImpl.class);

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Value("${" + PlatformConstants.CLOUD_TALK_TOKEN_KEY + "}")
    String cloudIntercomTokenKey;

    @Value("${" + PlatformConstants.LYKZ_ACCOUNT_SID + "}")
    String LYKZ_ACCOUNT_SID;
    @Value("${" + PlatformConstants.LYKZ_ACCOUNT_TOKEN + "}")
    String LYKZ_ACCOUNT_TOKEN;
    @Value("${" + PlatformConstants.LYKZ_APPID + "}")
    String LYKZ_APPID;
    @Value("${" + PlatformConstants.LYKZ_SOFT_VERSION + "}")
    String LYKZ_SOFT_VERSION;
    @Value("${" + PlatformConstants.LYKZ_URL + "}")
    String LYKZ_URL;
    @Value("${" + PlatformConstants.LYKZ_PORT + "}")
    String LYKZ_PORT;

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private Lock writeLock;
    private ExecutorService cachedThreadPool ;
    @PostConstruct
    public void init(){
        cachedThreadPool = Executors.newFixedThreadPool(100);
        writeLock = lock.writeLock();
    }

    @Autowired
    RedisService<CloudIntercomDeviceCacheVO> redisService;

    //云对讲持久层接口
    @Autowired
    IDeviceCloudIntercomInfoDao iDeviceCloudIntercomInfoDao;
    @Autowired
    IDeviceBusinessChangeLogDao iDeviceBusinessChangeLogDao;

    @Autowired
    ICloudIntercomDeviceServiceDao iCloudIntercomDeviceServiceDao;

    @Autowired
    IAppDevicePassRecordDao iAppDevicePassRecordDao;

    @Autowired
    ICloudElevatorDao iCloudElevatorDao;

    @Autowired
    IOperatePackageDao iOperatePackageDao;

    @Autowired
    private MessageSender messageSender;

    @Autowired
    IDeviceEntranceInfoDao iDeviceEntranceInfoDao;

    @Autowired
    IPropertyEquipDao iPropertyEquipDao;

    @Autowired
    IAppDeviceDao iAppDeviceDao;

    @Autowired
    private IAppDeviceService iAppDeviceService;

    @Autowired
    private RedisService redisServicePassTime;


    /**
     * <desc>
     * 判断sn是否存在
     * <desc/>
     *
     * @param sn
     * @return 记录数量
     * @author Chunjian.G
     * @createDate 2018-01-02
     */
    @Override
    public Integer checkSnExist(String sn) throws Exception {
        return iCloudIntercomDeviceServiceDao.checkSnExist(sn);
    }

    /**
     * <desc>
     *      根据sn查询云对讲设备业务服务器信息
     * <desc/>
     *
     * @param sn
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-15
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public CloudIntercomDeviceVO  getCloudIntercomServer(String sn) throws Exception {
        CloudIntercomDeviceVO serverVO = iCloudIntercomDeviceServiceDao.getCloudIntercomServer(sn);
        return serverVO;
    }

    /**
     * <desc>
     *      设备端连接云端认证
     * <desc/>
     *
     * @param sn
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-15
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public CloudIntercomDeviceVO cloudIntercomLogin(String sn,String newDevice) throws Exception {
        String projectId = StringHandlerUtil.getProjectIdBySn(sn);
        //1.设置云对讲token
        String token = UserTokenUtil.tokenEncrypt(sn, cloudIntercomTokenKey, SystemTypeEnum.OPERATE.getType());
        //token入库
        iCloudIntercomDeviceServiceDao.updateCoudIntercomToken(sn, token);
        //2.返回云对讲业务服务器信息
        CloudIntercomDeviceVO intercomDeviceVO = iCloudIntercomDeviceServiceDao.getCloudIntercomServer(sn);
        //新设备且没有分配过第三方通讯账号，分配账号给此设备
        if(StringUtils.isNotBlank(newDevice) && StringUtils.isBlank(intercomDeviceVO.getClientToken())){

            //根据项目编号和角色为开发者账号查询当前项目绑定的灵云快智的应用账号信息
            String lykzAppId = iCloudIntercomDeviceServiceDao.getBingLykzAppId(projectId, PropertyPublicRoleEnum.DEVELOPER.getRoleId());
            if(StringUtils.isNotEmpty(lykzAppId)){
                LYKZ_APPID = lykzAppId;
            }
            CloudIntercomAccountInfoPO accountInfoPO = this.createLykzDeviceAccount(LYKZ_APPID);
            if(accountInfoPO!=null){
                intercomDeviceVO.setClientToken(accountInfoPO.getToken());
                //更新当前设备的token
                iCloudIntercomDeviceServiceDao.updateDeviceAccountToken(sn,accountInfoPO.getCloudIntercomAccountId(),intercomDeviceVO.getClientToken());
            }
        }
        //更新设备的系统类型
        if(StringUtils.isNotBlank(newDevice)){
            iCloudIntercomDeviceServiceDao.updateSystemType(sn,2);
        }else{
            iCloudIntercomDeviceServiceDao.updateSystemType(sn,1);
        }
        intercomDeviceVO.setToken(token);
        intercomDeviceVO.setInvalidTime(DateUtil.fomatDate(
                DateUtils.addSeconds(new Date(), RedisConstant.CLOUD_INTERCOM_LOGIN_TIME.intValue()),
                "yyyy-MM-dd HH:mm:ss"
        ));
        //查询物业增值信息
        List<CloudIntercomDeviceVO.PropertyValue> list = iCloudIntercomDeviceServiceDao.getPropertyInfo(intercomDeviceVO.getProjectId(),1);
        if (list.size() == 0) {
            list = new ArrayList<>();
            list.add(new CloudIntercomDeviceVO.PropertyValue());
        }
        intercomDeviceVO.setDeploys(list);
        intercomDeviceVO.setDeviceEndTime("");
        CloudTalkIotInfoVO vo = iCloudIntercomDeviceServiceDao.getCloudTalkIotInfo(sn);
        //向阿里云iot中心注册设备 注册成功后更新设备信息
        if (vo.getIotDeviceId() == null) {
            Map<String, Object> params = new HashMap<>();
            params.put("deviceOperateIotType", DeviceIotEnum.REGIST_DEVICE.getCommandType());
            params.put("productKey", vo.getIotProductKey());
            params.put("deviceUnique",vo.getDeviceUnique());
            Map<String,Object> result=new HashMap<>();
            result.put("data",params);
            messageSender.send(RabbitMQConstant.RABBITMQ_DEVICE_ELEVATOR_QUEUE, JsonUtil.toJSON(result),
                    RabbitMQConstant.RABBITMQ_DEVICE_ELEVATOR_EXCHANGE,RabbitMQConstant.RABBITMQ_DEVICE_ELEVATOR_KEY);
            //偶发设备连接iot失败 原因设备异步注册iot 出现数据还未更新造成设备获取不到相应数据
            Thread.sleep(1000);
        }
        //3.将云对讲设备对象加入缓存
        CloudIntercomDeviceCacheVO cacheVO = new CloudIntercomDeviceCacheVO();
        BeanUtils.copyProperties(intercomDeviceVO, cacheVO);
        redisService.set(RedisConstant.CLOUD_INTERCOM_LOGIN_REDIS_KEY + sn,
                RedisConstant.CLOUD_INTERCOM_LOGIN_TIME, cacheVO);

        //4.重登录后清理过期轮询命令
        iCloudIntercomDeviceServiceDao.clearExpiredChangeLogOrder(sn);
        return intercomDeviceVO;
    }

    /**
     * <desc>
     * 从缓存中获取云对讲服务信息
     * </desc>
     *
     * @param token 云对讲设备token
     * @return
     * @author Jiaqi.X
     * @createDate 2017/10/12
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public CloudIntercomDeviceCacheVO retrieve(String token) throws Exception {
        try {
            if (StringUtils.isBlank(token)) {
                return null;
            }
            //解密拿到设备sn
            String sn = UserTokenUtil.tokenDecrypt(token, cloudIntercomTokenKey);
            if (sn == null) {
                return null;
            }
            CloudIntercomDeviceCacheVO serverVO =
                    redisService.getObject(RedisConstant.CLOUD_INTERCOM_LOGIN_REDIS_KEY + sn,
                            CloudIntercomDeviceCacheVO.class);
            if (serverVO == null){//缓存中没有相关数据
                //从数据库中取出token
                String tokenDb = iCloudIntercomDeviceServiceDao.getCloudIntercomToken(sn);
                if (StringUtils.isBlank(tokenDb) || !tokenDb.equals(token)){
                    return null;
                }
                //重新设置缓存
                CloudIntercomDeviceVO intercomDeviceVO = iCloudIntercomDeviceServiceDao.getCloudIntercomServer(sn);
                intercomDeviceVO.setToken(token);
                intercomDeviceVO.setInvalidTime(DateUtil.fomatDate(
                        DateUtils.addSeconds(new Date(), RedisConstant.CLOUD_INTERCOM_LOGIN_TIME.intValue()),
                        "yyyy-MM-dd HH:mm:ss"
                ));
                CloudIntercomDeviceCacheVO cacheVO = new CloudIntercomDeviceCacheVO();
                BeanUtils.copyProperties(intercomDeviceVO, cacheVO);
                redisService.set(RedisConstant.CLOUD_INTERCOM_LOGIN_REDIS_KEY + sn,
                        RedisConstant.CLOUD_INTERCOM_LOGIN_TIME, cacheVO);
                return cacheVO;
            }

            if (!token.equals(serverVO.getToken())){
                return null;
            }

            //重置缓存有效期
            redisService.set(RedisConstant.CLOUD_INTERCOM_LOGIN_REDIS_KEY + serverVO.getSn(),
                    RedisConstant.CLOUD_INTERCOM_LOGIN_TIME, serverVO);

            return serverVO;
        }catch (RedisConnectionFailureException e){
            throw new DataAccessException("云对讲retrieve【从缓存中获取云对讲信息】redis连接失败") ;
        }
    }

    /**
     * <desc>
     * 从缓存中获取云对讲服务信息
     * </desc>
     *
     * @param sn 云对讲设备sn
     * @return
     * @author Qiang.S
     * @createDate 2019/02/25
     */
    private CloudIntercomDeviceCacheVO retrieveBySn(String sn) throws Exception {
        try {
            if (StringUtils.isBlank(sn)) {
                return null;
            }
            CloudIntercomDeviceCacheVO serverVO =
                    redisService.getObject(RedisConstant.CLOUD_INTERCOM_LOGIN_REDIS_KEY + sn,
                            CloudIntercomDeviceCacheVO.class);
            if (serverVO == null){//缓存中没有相关数据
                //从数据库中取出token
                String tokenDb = iCloudIntercomDeviceServiceDao.getCloudIntercomToken(sn);
                if (StringUtils.isBlank(tokenDb)){
                    return null;
                }
                //重新设置缓存
                CloudIntercomDeviceVO intercomDeviceVO = iCloudIntercomDeviceServiceDao.getCloudIntercomServer(sn);
                intercomDeviceVO.setToken(tokenDb);
                intercomDeviceVO.setInvalidTime(DateUtil.fomatDate(
                        DateUtils.addSeconds(new Date(), RedisConstant.CLOUD_INTERCOM_LOGIN_TIME.intValue()),
                        "yyyy-MM-dd HH:mm:ss"
                ));
                CloudIntercomDeviceCacheVO cacheVO = new CloudIntercomDeviceCacheVO();
                BeanUtils.copyProperties(intercomDeviceVO, cacheVO);
                redisService.set(RedisConstant.CLOUD_INTERCOM_LOGIN_REDIS_KEY + sn,
                        RedisConstant.CLOUD_INTERCOM_LOGIN_TIME, cacheVO);
                return cacheVO;
            }
            //重置缓存有效期
            redisService.set(RedisConstant.CLOUD_INTERCOM_LOGIN_REDIS_KEY + serverVO.getSn(),
                    RedisConstant.CLOUD_INTERCOM_LOGIN_TIME, serverVO);

            return serverVO;
        }catch (RedisConnectionFailureException e){
            throw new DataAccessException("云对讲retrieve【从缓存中获取云对讲信息】redis连接失败") ;
        }
    }



    /**
     * <desc>
     *      设备端上电请求云端获取license与md5串
     * </desc>
     *
     * @param sn
     * @return
     * @author Jiaqi.X
     * @createDate 2017/11/20
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public DeviceCloudIntercomInfoPO getLicense(String sn){
        DeviceCloudIntercomInfoPO cloud=this.iCloudIntercomDeviceServiceDao.getCloudIntercomBySn(sn);
        return cloud;
    }

    /**
     * <desc>
     *       云端接收QQ与TinyID映射信息
     * </desc>
     *
     * @param sn 设备唯一码
     * @param din
     * @param qqTinyDTOS 映射信息列表
     * @return 未注册列表
     * @author Jiaqi.X
     * @createDate 2017/11/20
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<PropertyCloudQqTinyDTO> pushQQAndTinyId(String sn, String din, List<PropertyCloudQqTinyDTO> qqTinyDTOS) {
        //更新设备din
        iCloudIntercomDeviceServiceDao.updateDinBySn(sn,din);
        List<PropertyCloudQqTinyDTO> notFound=new ArrayList<>();
        if (null != qqTinyDTOS){
            qqTinyDTOS.forEach(qt->{
                if(iCloudIntercomDeviceServiceDao.updateUserProjectQqAndTinyId(qt.getQq(),qt.getTinyId())<1){
                    notFound.add(qt);
                }else{
                    iCloudIntercomDeviceServiceDao.updateUserRoomQqAndTinyId(qt.getQq(),qt.getTinyId());
                }
            });
        }
        return notFound;
    }

    /**
     * <desc>
     *      云端接收设备端的通行记录
     * </desc>
     *
     * @param sn
     * @param type  记录类型 4表示电话呼叫，7表示设备上密码通行
     * @param deviceRecordJson json映射信息
     * @param deviceType 设备类型 33云电梯 否则为云对讲
     * @return
     * @author Jiaqi.X
     * @createDate 2017/11/21
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer pushDeviceRecord(String sn,Integer type,String deviceRecordJson,String deviceType) throws Exception {
        String systemType = null;
        if ("99".equals(deviceType) ||"31".equals(deviceType) || "32".equals(deviceType) || "3".equals(deviceType)) {
            systemType = retrieveBySn(sn).getSystemType();
        }
        //LOG.info("systemType:"+systemType);
        Integer res = 0;
        String imageType = "png";
        if (PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType().toString().equals(deviceType)
                || PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString().equals(deviceType)
                || PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString().equals(deviceType)
                || PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString().equals(deviceType)) {
            List<Map<String,Object>> parseJson;
            try {
                parseJson = JsonUtil.decode(deviceRecordJson, new TypeReference<List<Map<String, Object>>>() {});
            } catch (IOException e) {
                LOG.error("云门禁pushDeviceRecord【云端接收设备端的通行记录】解析通行开门通行记录json失败", e);
                throw new Exception("云门禁pushDeviceRecord【云端接收设备端的通行记录】解析通行开门通行记录json失败", e);
            }
            for (Map<String, Object> map : parseJson) {
                if (map.get("type") == null) {
                    LOG.info("云门禁pushDeviceRecord【云端接收设备端的通行记录】解析通行开门通行记录json中type字段为空");
                    throw new Exception("云门禁pushDeviceRecord【云端接收设备端的通行记录】解析通行开门通行记录json中type字段为空");
                } else {
                    String entranceType = map.get("type").toString();
                    if ("7".equals(entranceType)) {
                        // 云门禁密码通行
                        TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                        po.setPdId(LogicIdUtil.bussinessId());
                        po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                        po.setDeviceType(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType());
                        po.setDeviceUnique(StringHandlerUtil.getProjectIdBySn(sn) + "2" + StringHandlerUtil.formatStrLen(map.get("doorNum").toString(),
                                "0",4,false,false));
                        po.setDeviceName(iAppDevicePassRecordDao.getEntranceNameByDeviceUnique(po.getDeviceUnique()));
                        po.setOpenType(OpenTypeEnum.BY_PASSWORD.getType());
                        try {
                            po.setPassTime(DateUtil.formatStringToDate(map.get("openTime").toString(), DateUtil.DATE_FORMAT_TYPE1));
                        } catch (ParseException e) {
                            LOG.error("云门禁pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                        }
                        po.setUploadTime(new Date());
                        if(map.containsKey("roomNum")){
                            po.setRoomNum(map.get("roomNum").toString());
                        }
                        po.setIsOpen(Integer.parseInt(map.get("isOpen").toString()));
                        po.setSynchro(0);
                        po.setSource(4);
                        po.setStatus(DataStatusEnum.NORMAL.getType());
                        po.setCreateTime(new Date());
                        po.setSource(4);
                        if (map.get("image") != null) {
                            //上传图片
                            InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(map.get("image").toString()));
                            po.setFacePicUrl(this.uploadFile(input,imageType));
                        }
                        res += iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
                    }
                    if ("8".equals(entranceType) || "11".equals(entranceType) || "17".equals(entranceType)) {
                        // 云门禁业主二维码开门通行
                        // 云门禁访客二维码开门通行
                        // 云门禁高级用户二维码开门通行
                        TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                        if (("8".equals(entranceType) || "17".equals(entranceType)) && map.get("uid") != null && StringUtils.isNotBlank(map.get("uid").toString())) {
                            String uid = map.get("uid").toString();
                            if(uid.length() > 8){
                                uid = uid.substring(uid.length() - 8,uid.length());
                            }
                            QrcodePassUserInfoVO vo = iPropertyEquipDao.findOwnerQrcodeInfoByUidAndProjectId(uid,StringHandlerUtil.getProjectIdBySn(sn));
                            if(vo==null){
                                continue;
                            }
                            po.setUserId(vo.getUserId());
                        }
                        po.setPdId(LogicIdUtil.bussinessId());
                        po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                        po.setDeviceType(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType());
                        po.setDeviceUnique(StringHandlerUtil.getProjectIdBySn(sn) + "2" + StringHandlerUtil.formatStrLen(map.get("doorNum").toString(),
                                "0",4,false,false));
                        po.setDeviceName(iAppDevicePassRecordDao.getEntranceNameByDeviceUnique(po.getDeviceUnique()));
                        if ("8".equals(entranceType)) {
                            po.setOpenType(OpenTypeEnum.BY_QRCODE.getType());
                        } else if ("11".equals(entranceType)) {
                            po.setOpenType(OpenTypeEnum.BY_VISTOR_QRCODE.getType());
                        } else {
                            po.setOpenType(OpenTypeEnum.BY_ADVANCED_QR_CODE.getType());
                        }
                        try {
                            po.setPassTime(DateUtil.formatStringToDate(map.get("openTime").toString(), DateUtil.DATE_FORMAT_TYPE1));
                        } catch (ParseException e) {
                            LOG.error("云门禁pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                        }
                        po.setUploadTime(new Date());
                        po.setIsOpen(Integer.parseInt(map.get("isOpen").toString()));
                        po.setSynchro(0);
                        po.setVisitorUuid(map.get("uid") == null ? null : map.get("uid").toString());
                        po.setSource(4);
                        po.setStatus(DataStatusEnum.NORMAL.getType());
                        po.setCreateTime(new Date());
                        if (map.get("image") != null) {
                            //上传图片
                            InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(map.get("image").toString()));
                            po.setFacePicUrl(this.uploadFile(input,imageType));
                        }
                        po.setSource(4);
                        res += iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                    }
                    if ("9".equals(entranceType)) {
                        //生成刷卡通行记录
                        TimeTaskDevicePassRecordPO po=new TimeTaskDevicePassRecordPO();
                        po.setPdId(LogicIdUtil.bussinessId());
                        po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                        po.setDeviceType(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType());
                        po.setDeviceUnique(StringHandlerUtil.getProjectIdBySn(sn) + "2" + StringHandlerUtil.formatStrLen(map.get("doorNum").toString(),
                                "0",4,false,false));
                        po.setDeviceName(iAppDevicePassRecordDao.getEntranceNameByDeviceUnique(po.getDeviceUnique()));
                        po.setOpenType(OpenTypeEnum.BY_CARD.getType());
                        try {
                            po.setPassTime(DateUtil.formatStringToDate(map.get("openTime").toString(), DateUtil.DATE_FORMAT_TYPE1));
                        } catch (ParseException e) {
                            LOG.error("云门禁pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                        }
                        po.setUploadTime(new Date());
                        po.setIsOpen(Integer.parseInt(map.get("isOpen").toString()));
                        po.setSynchro(0);
                        po.setSource(4);
                        po.setStatus(DataStatusEnum.NORMAL.getType());
                        po.setCreateTime(new Date());
                        if (map.get("image") != null) {
                            //上传图片
                            InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(map.get("image").toString()));
                            po.setFacePicUrl(this.uploadFile(input,imageType));
                        }
                        po.setSource(4);
                        res += iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                    }
                    if ("10".equals(entranceType)) {
                        // 云门禁8位离线密码通行记录
                        TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                        po.setPdId(LogicIdUtil.bussinessId());
                        po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                        po.setDeviceType(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType());
                        po.setDeviceUnique(StringHandlerUtil.getProjectIdBySn(sn) + "2" + StringHandlerUtil.formatStrLen(map.get("doorNum").toString(),
                                "0",4,false,false));
                        po.setDeviceName(iAppDevicePassRecordDao.getEntranceNameByDeviceUnique(po.getDeviceUnique()));
                        po.setOpenType(OpenTypeEnum.BY_DYNAMIC_PASSWORD.getType());
                        po.setDynamicPassword(map.get("dynamicPassword").toString());
                        try {
                            po.setPassTime(DateUtil.formatStringToDate(map.get("openTime").toString(), DateUtil.DATE_FORMAT_TYPE1));
                        } catch (ParseException e) {
                            LOG.error("云门禁pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                        }
                        po.setUploadTime(new Date());
                        if(map.containsKey("roomNum")){
                            po.setRoomNum(map.get("roomNum").toString());
                        }
                        po.setIsOpen(Integer.parseInt(map.get("isOpen").toString()));
                        po.setSynchro(0);
                        po.setSource(4);
                        po.setStatus(DataStatusEnum.NORMAL.getType());
                        po.setCreateTime(new Date());
                        if (map.get("image") != null) {
                            //上传图片
                            InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(map.get("image").toString()));
                            po.setFacePicUrl(this.uploadFile(input,imageType));
                        }
                        po.setSource(4);
                        res += iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
                    }
                    if ("13".equals(entranceType)) {
                        //此处休眠5秒是便于蓝牙呼梯通行记录的上传后 去重
                        Thread.sleep(5000);
                        // 云门禁IOT通行
                        if (map.get("correlationId") != null && StringUtils.isNotBlank(map.get("correlationId").toString())) {
                            TimeTaskDevicePassRecordPO po = iAppDevicePassRecordDao.getDevicePassRecordByCorrelationId(map.get("correlationId").toString());
                            if (po != null && map.get("correlationId").toString().equals(po.getCorrelationId())) {
                                //此时说明已经保存了蓝牙通行方式
                                //当IOT通行方式已经入库，需将能行方式改为 蓝牙+IOT 并推送给一卡通
                                iAppDevicePassRecordDao.updateOpenType(po.getCorrelationId());
                                //此处需注意处理 有可能通行记录已同步至设备子表中，故需在此处理子表通行方式
                                iAppDevicePassRecordDao.updateEntranceOpenType(po.getDeviceUnique(), DateUtil.fomatDate(po.getPassTime()),map.get("userId").toString());
                                continue;
                            }
                        }
                        TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                        po.setPdId(LogicIdUtil.bussinessId());
                        po.setUserId(map.get("userId").toString());
                        po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                        po.setDeviceType(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType());
                        po.setDeviceUnique(StringHandlerUtil.getProjectIdBySn(sn) + "2" + StringHandlerUtil.formatStrLen(map.get("doorNum").toString(),
                                "0",4,false,false));
                        po.setDeviceName(iAppDevicePassRecordDao.getEntranceNameByDeviceUnique(po.getDeviceUnique()));
                        po.setOpenType(OpenTypeEnum.BY_IOT_RECOGNITION.getType());
                        try {
                            po.setPassTime(DateUtil.formatStringToDate(map.get("openTime").toString(), DateUtil.DATE_FORMAT_TYPE1));
                        } catch (ParseException e) {
                            LOG.error("云门禁pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                        }
                        po.setUploadTime(new Date());
                        po.setIsOpen(Integer.parseInt(map.get("isOpen").toString()));
                        po.setSynchro(0);
                        po.setCorrelationId(map.get("correlationId").toString());
                        po.setStatus(DataStatusEnum.NORMAL.getType());
                        po.setCreateTime(new Date());
                        if (map.get("image") != null) {
                            //上传图片
                            InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(map.get("image").toString()));
                            po.setFacePicUrl(this.uploadFile(input,imageType));
                        }
                        po.setSource(4);
                        res += iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
                    }
                    if ("15".equals(entranceType)) {
                        //云门禁身份证开门
                        TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                        po.setPdId(LogicIdUtil.bussinessId());
                        po.setDeviceUnique(StringHandlerUtil.getProjectIdBySn(sn) + "2" + StringHandlerUtil.formatStrLen(map.get("doorNum").toString(),
                                "0",4,false,false));
                        String userId = iCloudIntercomDeviceServiceDao.getEntranceUserIdByIdcardKey(map.get("idcardKey").toString(),StringHandlerUtil.getProjectIdBySn(sn),po.getDeviceUnique());
                        if (StringUtils.isBlank(userId)) {
                            // 判断是否为业主临时权限通行
                            userId = iCloudIntercomDeviceServiceDao.getUserIdByCdcardKey(map.get("idcardKey").toString(), StringHandlerUtil.getProjectIdBySn(sn));
                            if (StringUtils.isBlank(userId)) {
                                userId = iCloudIntercomDeviceServiceDao.getVisitorByIdcardKey(map.get("idcardKey").toString(), StringHandlerUtil.getProjectIdBySn(sn));
                                po.setOpenType(OpenTypeEnum.BY_VISITOR_IDCARD_KEY.getType());
                            } else {
                                List<AppDoorDevicesVO> doorDevices = iAppDeviceService.getDoorDevices(userId, StringHandlerUtil.getProjectIdBySn(sn), 0);
                                List<AppUserDevicesVO> tempList = iAppDeviceService.getUserDevicesInfo(userId, StringHandlerUtil.getProjectIdBySn(sn));
                                for (AppDoorDevicesVO doorDevice : doorDevices) {
                                    if (doorDevice.getDeviceUnique().equals(po.getDeviceUnique())) {
                                        po.setOpenType(OpenTypeEnum.BY_IDCARD_KEY.getType());
                                        break;
                                    }
                                }
                                for (AppUserDevicesVO temp : tempList) {
                                    if (temp.getDeviceUnique().equals(po.getDeviceUnique())) {
                                        po.setOpenType(OpenTypeEnum.BY_IDCARD_KEY.getType());
                                        break;
                                    }
                                }
                                if (po.getOpenType() == null) {
                                    po.setOpenType(OpenTypeEnum.BY_VISITOR_IDCARD_KEY.getType());
                                }
                            }
                        } else {
                            po.setOpenType(OpenTypeEnum.BY_IDCARD_KEY.getType());
                        }
                        //LOG.info("身份证userId:"+userId+"idcardKey:"+map.get("idcardKey")+"projectId:"+StringHandlerUtil.getProjectIdBySn(sn));
                        po.setUserId(userId);
                        po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                        po.setDeviceType(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType());
                        po.setDeviceName(iAppDevicePassRecordDao.getEntranceNameByDeviceUnique(po.getDeviceUnique()));
                        try {
                            po.setPassTime(DateUtil.formatStringToDate(map.get("openTime").toString(), DateUtil.DATE_FORMAT_TYPE1));
                        } catch (ParseException e) {
                            LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                        }
                        po.setUploadTime(new Date());
                        po.setIsOpen(Integer.parseInt(map.get("isOpen").toString()));
                        po.setSynchro(0);
                        po.setStatus(DataStatusEnum.NORMAL.getType());
                        po.setCreateTime(new Date());
                        if (map.get("image") != null) {
                            //上传图片
                            InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(map.get("image").toString()));
                            po.setFacePicUrl(this.uploadFile(input,imageType));
                        }
                        po.setSource(4);
                        res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                    }
                    if ("12".equals(entranceType) || "14".equals(entranceType)) {
                        // 云门禁人脸识别通行记录
                        TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                        po.setPdId(LogicIdUtil.bussinessId());
                        po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                        po.setDeviceType(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType());
                        po.setDeviceUnique(StringHandlerUtil.getProjectIdBySn(sn) + "2" + StringHandlerUtil.formatStrLen(map.get("doorNum").toString(),
                                "0",4,false,false));
                        po.setDeviceName(iAppDevicePassRecordDao.getEntranceNameByDeviceUnique(po.getDeviceUnique()));
                        po.setOpenType("12".equals(entranceType)?OpenTypeEnum.BY_FACE_RECOGNITION.getType():OpenTypeEnum.BY_VISITOR_FACE.getType());
                        po.setUserId(map.get("userId") != null?map.get("userId").toString():"");
                        try {
                            po.setPassTime(DateUtil.formatStringToDate(map.get("openTime").toString(), DateUtil.DATE_FORMAT_TYPE1));
                        } catch (ParseException e) {
                            LOG.error("云门禁pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                        }
                        po.setUploadTime(new Date());
                        po.setIsOpen(Integer.parseInt(map.get("isOpen").toString()));
                        po.setSynchro(0);
                        po.setStatus(DataStatusEnum.NORMAL.getType());
                        po.setCreateTime(new Date());
                        if (map.get("image") != null) {
                            //上传图片
                            InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(map.get("image").toString()));
                            po.setFacePicUrl(this.uploadFile(input,imageType));
                        }
                        po.setSource(4);
                        res += iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
                    }
                }
            }
            return res;
        }
        JSONArray jsonArray = JSONArray.parseArray(deviceRecordJson);
        for (Object json : jsonArray) {
            JSONObject jsonObject = (JSONObject) json;
            deviceRecordJson = "["+json.toString()+"]";
            if (jsonObject.get("type") != null) {
                type = Integer.parseInt(jsonObject.get("type").toString());
            }
            if(type == 4){
                //电话呼叫
                List<CloudTalkPhoneCallPassDTO> phones;
                try {
                    phones=(List<CloudTalkPhoneCallPassDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudTalkPhoneCallPassDTO.class);
                } catch (IOException e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析电话呼叫通行记录json失败", e);
                }
                for(CloudTalkPhoneCallPassDTO phone : phones){
                    TimeTaskDevicePassRecordPO po=new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setDeviceType(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType() : PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                    po.setDeviceUnique(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            StringHandlerUtil.getElevatorDeviceUniqueBySn(sn) : StringHandlerUtil.getDeviceUniqueBySn(sn));
                    po.setDeviceName(iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                    po.setOpenType(OpenTypeEnum.BY_PHONE.getType());
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(phone.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                    }
                    po.setUploadTime(new Date());
                    po.setRoomNum(phone.getRoomNum());
                    po.setIsOpen(phone.getIsOpen());
                    po.setBeginVisitTime(DateUtil.formatStringToDate(phone.getBeginVisitTime(), DateUtil.DATE_FORMAT_TYPE1));
                    po.setEndVisitTime(DateUtil.formatStringToDate(phone.getEndVisitTime(), DateUtil.DATE_FORMAT_TYPE1));
                    po.setCallPhoneNo(phone.getPhoneNo());
                    po.setSynchro(0);
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    if (systemType != null && "2".equals(systemType) && phone.getImage() != null && !"".equals(phone.getImage())) {//安卓云对讲
                        //上传图片
                        InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(phone.getImage()));
                        po.setFacePicUrl(this.uploadFile(input,imageType));
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
                }
            }else if(!"17".equals(deviceType) && !"22".equals(deviceType) && type == 7){
                //密码通行
                List<CloudTalkPwdPassDTO> pwd;
                try {
                    pwd=(List<CloudTalkPwdPassDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudTalkPwdPassDTO.class);
                } catch (IOException e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析密码开门通行记录json失败", e);
                }
                for(CloudTalkPwdPassDTO password : pwd){
                    TimeTaskDevicePassRecordPO po=new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setDeviceType(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType() : PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                    po.setDeviceUnique(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            StringHandlerUtil.getElevatorDeviceUniqueBySn(sn) : StringHandlerUtil.getDeviceUniqueBySn(sn));
                    po.setDeviceName(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            iCloudElevatorDao.getElevatorNameBySn(sn) : iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                    po.setOpenType(OpenTypeEnum.BY_PASSWORD.getType());
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(password.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                    }
                    po.setUploadTime(new Date());
                    po.setRoomNum(password.getRoomNum());
                    po.setIsOpen(password.getIsOpen());
                    po.setSynchro(0);
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    if (systemType != null && "2".equals(systemType) && password.getImage() != null && !"".equals(password.getImage())) {//安卓云对讲
                        //上传图片
                        InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(password.getImage()));
                        po.setFacePicUrl(this.uploadFile(input,imageType));
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
                }
            } else if (type == 12) {
                //人脸识别
                List<CloudTalkFacePassDTO> faces;
                try {
                    faces = (List<CloudTalkFacePassDTO>) JsonUtil.toListObject(deviceRecordJson, ArrayList.class, CloudTalkFacePassDTO.class);
                } catch (IOException e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析密码开门通行记录json失败", e);
                }
                TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                po.setPdId(LogicIdUtil.bussinessId());
                po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                po.setDeviceType(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                        PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType() : PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                po.setDeviceUnique(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                        StringHandlerUtil.getElevatorDeviceUniqueBySn(sn) : StringHandlerUtil.getDeviceUniqueBySn(sn));
                po.setDeviceName(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                        iCloudElevatorDao.getElevatorNameBySn(sn) : iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                po.setOpenType(OpenTypeEnum.BY_FACE_RECOGNITION.getType());
                po.setUploadTime(new Date());
                po.setIsOpen(1);
                po.setSynchro(0);
                po.setStatus(DataStatusEnum.NORMAL.getType());
                po.setCreateTime(new Date());
                po.setSource(4);
                for (CloudTalkFacePassDTO face : faces) {
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(face.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                    }
                    po.setUserId(face.getUserId());
                    //上传图片
                    InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(face.getImage()));
                    po.setFacePicUrl(this.uploadFile(input,imageType));
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
                }
            } else if (!"17".equals(deviceType) && !"22".equals(deviceType) && type == 11) {
                //访客二维码通行
                List<CloudTalkVisitorQrPassDTO> visitorQr;
                try {
                    visitorQr = (List<CloudTalkVisitorQrPassDTO>) JsonUtil.toListObject(deviceRecordJson, ArrayList.class, CloudTalkVisitorQrPassDTO.class);
                    //visitorQr = JSONObject.parseObject(deviceRecordJson,CloudTalkVisitorQrPassDTO.class);
                } catch (Exception e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析访客二维码开门通行记录json失败", e);
                }
                for (CloudTalkVisitorQrPassDTO qr : visitorQr) {
                    TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setUserId(qr.getQrcode().substring(4,15));
                    po.setDeviceType(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType() : PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                    po.setDeviceUnique(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            StringHandlerUtil.getElevatorDeviceUniqueBySn(sn) : StringHandlerUtil.getDeviceUniqueBySn(sn));
                    po.setDeviceName(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            iCloudElevatorDao.getElevatorNameBySn(sn) : iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                    po.setOpenType(OpenTypeEnum.BY_VISTOR_QRCODE.getType());
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(qr.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                    }
                    po.setUploadTime(new Date());
                    po.setIsOpen(qr.getIsOpen());
                    po.setSynchro(0);
                    po.setQrcode(qr.getQrcode());
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    if (systemType != null && "2".equals(systemType) && qr.getImage() != null && !"".equals(qr.getImage())) {//安卓云对讲
                        //上传图片
                        InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(qr.getImage()));
                        po.setFacePicUrl(this.uploadFile(input,imageType));
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                }
            }else if(type == 10 && !"17".equals(deviceType) && !"22".equals(deviceType)){
                //动态密码
                List<CloudTalkDynamicPasswordDTO> visitors;
                try {
                    visitors=(List<CloudTalkDynamicPasswordDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudTalkDynamicPasswordDTO.class);
                    //visitorQr = JSONObject.parseObject(deviceRecordJson,CloudTalkVisitorQrPassDTO.class);
                } catch (Exception e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析业主二维码开门通行记录json失败", e);
                }
                for(CloudTalkDynamicPasswordDTO qr : visitors) {
                    TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setDeviceType(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType() : PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                    po.setDeviceUnique(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            StringHandlerUtil.getElevatorDeviceUniqueBySn(sn) : StringHandlerUtil.getDeviceUniqueBySn(sn));
                    po.setDeviceName(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            iCloudElevatorDao.getElevatorNameBySn(sn) : iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                    po.setOpenType(OpenTypeEnum.BY_DYNAMIC_PASSWORD.getType());
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(qr.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                    }
                    po.setRoomNum(qr.getRoomNum());
                    po.setUploadTime(new Date());
                    po.setIsOpen(qr.getIsOpen());
                    po.setSynchro(0);
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    if (systemType != null && "2".equals(systemType) && qr.getImage() != null && !"".equals(qr.getImage())) {//安卓云对讲
                        //上传图片
                        InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(qr.getImage()));
                        po.setFacePicUrl(this.uploadFile(input,imageType));
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                }
            } else if (!"17".equals(deviceType) && !"22".equals(deviceType) && type == 8) {
                //业主二维码通行
                List<CloudTalkVisitorQrPassDTO> visitorQr;
                try {
                    visitorQr = (List<CloudTalkVisitorQrPassDTO>) JsonUtil.toListObject(deviceRecordJson, ArrayList.class, CloudTalkVisitorQrPassDTO.class);
                    //visitorQr = JSONObject.parseObject(deviceRecordJson,CloudTalkVisitorQrPassDTO.class);
                } catch (Exception e){
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析业主二维码开门通行记录json失败", e);
                }
                for (CloudTalkVisitorQrPassDTO qr : visitorQr) {
                    TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    if (qr.getQrcode() != null && qr.getQrcode().length() > 15) {
                        po.setUserId(iCloudIntercomDeviceServiceDao.getUserIdByPhone(qr.getQrcode().substring(4,15)));
                        //LOG.info("业主二维码:"+qr.getQrcode() + " 手机:" + qr.getQrcode().substring(4,15));
                        if(StringUtils.isBlank(po.getUserId())){
                            po.setUserId(qr.getQrcode().substring(4,15));
                        }
                    }
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setDeviceType(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType() : PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                    po.setDeviceUnique(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            StringHandlerUtil.getElevatorDeviceUniqueBySn(sn) : StringHandlerUtil.getDeviceUniqueBySn(sn));
                    po.setDeviceName(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            iCloudElevatorDao.getElevatorNameBySn(sn) : iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                    po.setOpenType(OpenTypeEnum.BY_QRCODE.getType());
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(qr.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                    }
                    po.setUploadTime(new Date());
                    po.setIsOpen(qr.getIsOpen());
                    po.setSynchro(0);
                    po.setQrcode(qr.getQrcode());
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    if (systemType != null && "2".equals(systemType) && qr.getImage() != null && !"".equals(qr.getImage())) {//安卓云对讲
                        //上传图片
                        InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(qr.getImage()));
                        po.setFacePicUrl(this.uploadFile(input,imageType));
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                }
            }else if((type == 5 || type == 6) && systemType != null && "2".equals(systemType)){
                //安卓云对讲访客开门
                List<CloudTalkTCPPassDTO> TCPPass;
                try {
                    TCPPass=(List<CloudTalkTCPPassDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudTalkTCPPassDTO.class);
                } catch (Exception e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析安卓云对讲tcp开门通行记录json失败", e);
                }
                for(CloudTalkTCPPassDTO tcp : TCPPass) {
                    TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    po.setUserId(tcp.getUserId());
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setDeviceType(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                    po.setDeviceUnique(StringHandlerUtil.getDeviceUniqueBySn(sn));
                    po.setDeviceName(iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                    po.setOpenType(type == 5?OpenTypeEnum.BY_VISTOR.getType():OpenTypeEnum.BY_OWN.getType());
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(tcp.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                    }
                    po.setUploadTime(new Date());
                    po.setIsOpen(tcp.getIsOpen());
                    po.setSynchro(0);
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    if (tcp.getImage() != null && !"".equals(tcp.getImage())) {//安卓云对讲
                        //上传图片
                        InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(tcp.getImage()));
                        po.setFacePicUrl(this.uploadFile(input, imageType));
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                }
            }else if(type == 14 && systemType != null){
                //安卓云对讲访客人脸通行
                List<CloudTalkVisitorFacePassDTO> visitorFace;
                try {
                    visitorFace=(List<CloudTalkVisitorFacePassDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudTalkVisitorFacePassDTO.class);
                } catch (Exception e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析安卓云对讲访客人脸开门通行记录json失败", e);
                }
                for(CloudTalkVisitorFacePassDTO face : visitorFace) {
                    TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    po.setUserId(face.getUserId());
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setDeviceType(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                    po.setDeviceUnique(StringHandlerUtil.getDeviceUniqueBySn(sn));
                    po.setDeviceName(iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                    po.setOpenType(OpenTypeEnum.BY_VISITOR_FACE.getType());
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(face.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                    }
                    po.setUploadTime(new Date());
                    po.setIsOpen(face.getIsOpen());
                    po.setSynchro(0);
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    if (face.getImage() != null && !"".equals(face.getImage())) {
                        //上传图片
                        InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(face.getImage()));
                        po.setFacePicUrl(this.uploadFile(input, imageType));
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                }
            } else if (!"17".equals(deviceType) && !"22".equals(deviceType) && type == 15) {
                //云对讲身份证开门
                List<CloudTalkIdcardPassDTO> idcardPass;
                try {
                    idcardPass=(List<CloudTalkIdcardPassDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudTalkIdcardPassDTO.class);
                } catch (Exception e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析身份证开门通行记录json失败", e);
                }
                for(CloudTalkIdcardPassDTO idcard : idcardPass) {
                    TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    if (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())) {//云电梯
                        po.setDeviceType(PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType());
                        po.setDeviceUnique(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn));
                    } else {//云对讲
                        po.setDeviceType(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                        po.setDeviceUnique(StringHandlerUtil.getDeviceUniqueBySn(sn));
                    }
                    String userId = null;
                    if (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())) {
                        userId = iCloudIntercomDeviceServiceDao.getElevatorUserIdByIdcardKey(idcard.getIdcardKey(),StringHandlerUtil.getProjectIdBySn(sn),
                                StringHandlerUtil.getElevatorDeviceUniqueBySn(sn));
                    }/* else {
                        userId = iCloudIntercomDeviceServiceDao.getUserIdByCdcardKey(idcard.getIdcardKey(),StringHandlerUtil.getProjectIdBySn(sn));
                    }*/
                    if (StringUtils.isBlank(userId)) {
                        // 判断是否为业主电梯临时权限通行或云对讲的业主or访客通行方式
                        userId = iCloudIntercomDeviceServiceDao.getUserIdByCdcardKey(idcard.getIdcardKey(), StringHandlerUtil.getProjectIdBySn(sn));
                        if (StringUtils.isBlank(userId)) {
                            userId = iCloudIntercomDeviceServiceDao.getVisitorByIdcardKey(idcard.getIdcardKey(), StringHandlerUtil.getProjectIdBySn(sn));
                            po.setOpenType(OpenTypeEnum.BY_VISITOR_IDCARD_KEY.getType());
                        } else {
                            List<AppFloorDevicesVO> floorDevices = iAppDeviceService.getFloorDevices(userId, StringHandlerUtil.getProjectIdBySn(sn), 0);
                            List<AppCloudIntercomsVO> cloudIntercoms = iAppDeviceService.getCloudIntercoms(userId, StringHandlerUtil.getProjectIdBySn(sn), 0);
                            for (AppFloorDevicesVO floorDevice : floorDevices) {
                                if (floorDevice.getDeviceUnique().equals(po.getDeviceUnique())) {
                                    po.setOpenType(OpenTypeEnum.BY_IDCARD_KEY.getType());
                                    break;
                                }
                            }
                            if (po.getOpenType() == null) {
                                for (AppCloudIntercomsVO cloudIntercom : cloudIntercoms) {
                                    if (cloudIntercom.getDeviceUnique().equals(po.getDeviceUnique())) {
                                        po.setOpenType(OpenTypeEnum.BY_IDCARD_KEY.getType());
                                        break;
                                    }
                                }
                                if (po.getOpenType() == null) {
                                    po.setOpenType(OpenTypeEnum.BY_VISITOR_IDCARD_KEY.getType());
                                }
                            }
                        }
                    } else {
                        po.setOpenType(OpenTypeEnum.BY_IDCARD_KEY.getType());
                    }
                    //LOG.info("身份证userId:"+userId+"idcardKey:"+idcard.getIdcardKey()+"projectId:"+StringHandlerUtil.getProjectIdBySn(sn));
                    po.setUserId(userId);
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setDeviceName(deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) ?
                            iCloudElevatorDao.getElevatorNameBySn(sn) : iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));

                    try {
                        po.setPassTime(DateUtil.formatStringToDate(idcard.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                    }
                    po.setUploadTime(new Date());
                    po.setIsOpen(idcard.getIsOpen());
                    po.setSynchro(0);
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    if (systemType != null && "2".equals(systemType) && idcard.getImage() != null && !"".equals(idcard.getImage())) {//安卓云对讲
                        //上传图片
                        InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(idcard.getImage()));
                        po.setFacePicUrl(this.uploadFile(input,imageType));
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                }
            }else if((type == 9 || type == 16) && systemType != null && "2".equals(systemType)){
                //安卓云对讲刷卡开门 或 安卓云对讲一卡通开门
                List<CloudTalkOthersPassDTO> otherPass;
                try {
                    otherPass=(List<CloudTalkOthersPassDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudTalkOthersPassDTO.class);
                } catch (Exception e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析安卓云对讲刷卡或一卡通开门通行记录json失败", e);
                }
                for(CloudTalkOthersPassDTO others : otherPass) {
                    TimeTaskDevicePassRecordPO po = new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setDeviceType(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                    po.setDeviceUnique(StringHandlerUtil.getDeviceUniqueBySn(sn));
                    po.setDeviceName(iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                    po.setOpenType(type == 9?OpenTypeEnum.BY_CARD.getType():OpenTypeEnum.BY_SMART_CARD.getType());
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(others.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null", e);
                    }
                    po.setUploadTime(new Date());
                    po.setIsOpen(others.getIsOpen());
                    po.setSynchro(0);
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    if (others.getImage() != null && !"".equals(others.getImage())) {//安卓云对讲
                        //上传图片
                        InputStream input = new ByteArrayInputStream(StringHandlerUtil.imageBase64StrToByte(others.getImage()));
                        po.setFacePicUrl(this.uploadFile(input,imageType));
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                }
            }else if(type == 9  && (PropertyEquipTypeEnum.CLOUD_ELEVATOR.getType().toString().equals(deviceType)
                    || PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType().toString().equals(deviceType)
                    || PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString().equals(deviceType))){
                //云电梯刷卡上传通行记录
                List<CloudElevatorCardPassDTO> cards;
                try {
                    cards=(List<CloudElevatorCardPassDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudElevatorCardPassDTO.class);
                } catch (IOException e) {
                    throw new Exception("pushDeviceRecord【云端接收设备端的通行记录】解析云电梯刷卡通行记录json失败", e);
                }
                //根据項目Id查询收费间隔时间 如同一个用户相同通行方式在收费间隔时间内只扣一次
                Integer feeIntervalTime = Integer.parseInt(iCloudElevatorDao.getFeeConfigTimeByProjectId(StringHandlerUtil.getProjectIdBySn(sn)));
                //查询项目的预警次数
                Integer warningTimes = iCloudElevatorDao.getWarningTimesByProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                for(CloudElevatorCardPassDTO card : cards){
                    boolean  mark = true;
                    boolean pushBlackList = false;
                    TimeTaskDevicePassRecordPO po=new TimeTaskDevicePassRecordPO();
                    po.setPdId(LogicIdUtil.bussinessId());
                    po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                    po.setDeviceType(PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType());
                    po.setDeviceUnique(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn));
                    po.setDeviceName(iCloudElevatorDao.getElevatorNameBySn(sn));
                    if(9==card.getUserType()){
                        po.setOpenType(OpenTypeEnum.BY_PASSWORD.getType());
                    }else{
                        po.setOpenType(OpenTypeEnum.BY_CARD.getType());
                    }
                    try {
                        po.setPassTime(DateUtil.formatStringToDate(card.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                    } catch (ParseException e) {
                        LOG.error("pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                    }
                    po.setUploadTime(new Date());
                    po.setIsOpen(0);
                    po.setSynchro(0);
                    po.setStatus(DataStatusEnum.NORMAL.getType());
                    po.setCreateTime(new Date());
                    po.setUserId(card.getCardId());

                    //查询用户相同通行方式的最近一次记录
                    String lastTime = redisServicePassTime.get(String.format("%s%s%s%s",RedisConstant.REDIS_PASS_TIME_KEY_CACHE,StringHandlerUtil.getProjectIdBySn(sn),card.getCardId(),"9"));
                    //String lastTime = iCloudElevatorDao.getLastPassTimeByProjectId(StringHandlerUtil.getProjectIdBySn(sn),card.getCardId(),"9");
                    if(StringUtils.isNotEmpty(lastTime) && feeIntervalTime!=0){
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Map<String,Object> map = DateUtil.reckonDate(dateFormat.format(DateUtil.formatStringToDate(card.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1)),lastTime);
                        Integer passTimeInterval = Integer.parseInt((map.get("s")).toString());
                        if(passTimeInterval <= feeIntervalTime){
                            mark = false;
                        }else{
                            redisServicePassTime.set(String.format("%s%s%s%s",RedisConstant.REDIS_PASS_TIME_KEY_CACHE,StringHandlerUtil.getProjectIdBySn(sn),card.getCardId(),"9"),RedisConstant.REDIS_PASS_TIME_KEY_CACHE_TIME,card.getOpenTime());
                        }
                    }else{
                        redisServicePassTime.set(String.format("%s%s%s%s",RedisConstant.REDIS_PASS_TIME_KEY_CACHE,StringHandlerUtil.getProjectIdBySn(sn),card.getCardId(),"9"),RedisConstant.REDIS_PASS_TIME_KEY_CACHE_TIME,card.getOpenTime());
                    }
                    //根据卡号查询卡号所对应的房间及次数信息
                    CloudElevatorCardPassInfoVO vo = iCloudElevatorDao.getRoomInfoByCardId(StringHandlerUtil.getProjectIdBySn(sn),card.getCardId());
                    //查询电梯计费模式的状态
                    Integer equipMode = iCloudElevatorDao.getEquipModeBySn(sn);
                    //高级用户卡不参与计次 处理扣次逻辑
                    if(vo != null && 3==card.getUserType() && vo.getChargeMode() != null && vo.getChargeMode()==2 && equipMode!= null && equipMode == 2){
                        if(mark){
                            //组装消费记录表信息
                            ConsumeRecordInfoPO consumeRecordInfoPO = new ConsumeRecordInfoPO();
                            consumeRecordInfoPO.setConsumeId(LogicIdUtil.bussinessId());
                            consumeRecordInfoPO.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                            consumeRecordInfoPO.setDeviceUnique(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn));
                            consumeRecordInfoPO.setPassTime(po.getPassTime());
                            consumeRecordInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                            consumeRecordInfoPO.setCreateTime(new Date());
                            consumeRecordInfoPO.setUpdateTime(new Date());
                            consumeRecordInfoPO.setUserInfo(card.getCardId());
                            consumeRecordInfoPO.setHousesType(2);
                            consumeRecordInfoPO.setPassType(2);
                            consumeRecordInfoPO.setCreateUserId(card.getCardId());
                            consumeRecordInfoPO.setOperateUserId(card.getCardId());
                            consumeRecordInfoPO.setRoomId(vo.getRoomId());

                            po.setLastPassCount(vo.getUsableCount()-1);
                            consumeRecordInfoPO.setLastPassCount(vo.getUsableCount()-1);
                            if (StringUtils.isNotBlank(vo.getQrcodeBatchRecordId())) {
                                Integer row = iPropertyEquipDao.updateQrcodeRoomCount(vo.getQrcodeBatchRecordId(), vo.getUsableCount() > 1 ? 1 : 0);
                                if (row < 1 || vo.getUsableCount() <= 1 || (vo.getUsableCount()-1 == warningTimes)) {
                                    //推送黑名单数据
                                    pushBlackList = true;
                                }
                            }
                            //如果扣次则保存消费记录
                            iAppDevicePassRecordDao.save(SqlUtil.durableData(consumeRecordInfoPO,PlatformConstants.TABLE_SAVE));
                        }
                        if(!mark){
                            po.setLastPassCount(vo.getUsableCount());
                        }
                    }
                    if(vo==null && 3==card.getUserType() && equipMode!= null && equipMode == 2){
                        //处理设备掉线时，发行了用户卡，进行刷卡，设备开放正常
                        //将设备网络恢复正常，设备网络恢复后再刷卡，设备不开放。但是之前设备掉线时刷卡的次数没有被减掉
                        Map<String,Object> map = iCloudElevatorDao.getChargeModeByProjectId(StringHandlerUtil.getProjectIdBySn(sn),card.getCardId());
                        if(map!=null && map.get("chargeMode").toString().equals("2")){
                            PropertyRoomQrcodeBatchRecordPO propertyRoomQrcodeBatchRecordPO = new PropertyRoomQrcodeBatchRecordPO();
                            propertyRoomQrcodeBatchRecordPO.setQrcodeBatchRecordId(LogicIdUtil.bussinessId());
                            propertyRoomQrcodeBatchRecordPO.setRoomId(map.get("roomId")==null?"":map.get("roomId").toString());
                            propertyRoomQrcodeBatchRecordPO.setBatch(1);
                            propertyRoomQrcodeBatchRecordPO.setPayCount(0);
                            propertyRoomQrcodeBatchRecordPO.setCount(0);
                            propertyRoomQrcodeBatchRecordPO.setUsableCount(-1);
                            propertyRoomQrcodeBatchRecordPO.setStatus(DataStatusEnum.NORMAL.getType());
                            propertyRoomQrcodeBatchRecordPO.setCreateTime(new Date());
                            propertyRoomQrcodeBatchRecordPO.setUpdateTime(new Date());

                            //组装消费记录表信息
                            ConsumeRecordInfoPO consumeRecordInfoPO = new ConsumeRecordInfoPO();
                            consumeRecordInfoPO.setConsumeId(LogicIdUtil.bussinessId());
                            consumeRecordInfoPO.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                            consumeRecordInfoPO.setDeviceUnique(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn));
                            consumeRecordInfoPO.setPassTime(po.getPassTime());
                            consumeRecordInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                            consumeRecordInfoPO.setCreateTime(new Date());
                            consumeRecordInfoPO.setUpdateTime(new Date());
                            consumeRecordInfoPO.setUserInfo(card.getCardId());
                            consumeRecordInfoPO.setHousesType(2);
                            consumeRecordInfoPO.setPassType(2);
                            consumeRecordInfoPO.setCreateUserId(card.getCardId());
                            consumeRecordInfoPO.setOperateUserId(card.getCardId());
                            consumeRecordInfoPO.setRoomId(map.get("roomId").toString());

                            po.setLastPassCount(-1);
                            consumeRecordInfoPO.setLastPassCount(-1);
                            iAppDevicePassRecordDao.save(SqlUtil.durableData(propertyRoomQrcodeBatchRecordPO, PlatformConstants.TABLE_SAVE));
                            //如果扣次则保存消费记录
                            iAppDevicePassRecordDao.save(SqlUtil.durableData(consumeRecordInfoPO,PlatformConstants.TABLE_SAVE));
                        }
                    }
                    if(pushBlackList && vo!=null){
                        //推送数据
                        //推送黑名单更新数据
                        List<DeviceBusinessElevatorChangeLogPO> elevatorChanges = new ArrayList<>();
                        Map<String,Object> blackList = new HashMap<>();
                        blackList.put("projectId", StringHandlerUtil.getProjectIdBySn(sn));
                        blackList.put("roomId", vo.getRoomId());
                        blackList.put("version",0);
                        DeviceBusinessElevatorChangeLogPO elevatorPo = new DeviceBusinessElevatorChangeLogPO(StringHandlerUtil.getProjectIdBySn(sn), CloudElevatorChangeBusinessEnum.PUSH_BLACK_LIST, JsonUtil.toJSON(blackList));
                        elevatorChanges.add(elevatorPo);
                        JSONObject pushJs = new JSONObject();
                        pushJs.put("data", elevatorChanges);
                        //推送云电梯业务指令
                        messageSender.send(
                                RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ELEVATOR_CHANGE_BUSINESS_QUEUE,
                                JsonUtil.toJSON(pushJs),
                                RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_EXCHANGE,
                                RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_ROUTING_KEY);
                    }
                    po.setSource(4);
                    res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
                }
            }
        }
        return res;
    }

    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @param fileType 文件类型
     * @return 文件上传成功后会返回Url,否则返回空
     * @author Qiang.S
     * @createDate 2019/02/22
     */
    private String uploadFile(InputStream inputStream, String fileType) throws IOException {
        String fileUrl = "";
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                fileType,
                FILE_ACCESS_URL,
                FileCatalogEnum.FACE_PASS_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }

        /**
         * <desc>
         *      云端接收H5端上传的通行记录
         * </desc>
         *
         * @param sn 云对讲sn
         * @param type 2表示QQ呼叫 3表示用户本人通行
         * @param deviceRecordJson json数据
         * @return
         * @author Jiaqi.X
         * @createDate 2017/11/22
         */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer pushQqRecord(String sn,Integer type,String deviceRecordJson) throws Exception {
        Integer res = 0;
        if(type == 2){
            //访客呼叫QQ记录
            List<CloudTalkQqDTO> qqs;
            try {
                qqs=(List<CloudTalkQqDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudTalkQqDTO.class);
            } catch (IOException e) {
                throw new Exception("云对讲pushQqRecord【云端接收H5端上传的通行记录】解析访客呼叫QQ记录json失败",e);
            }
            for(CloudTalkQqDTO qq : qqs){
                TimeTaskDevicePassRecordPO po=new TimeTaskDevicePassRecordPO();
                po.setPdId(LogicIdUtil.bussinessId());
                po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                po.setDeviceType(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                po.setDeviceUnique(StringHandlerUtil.getDeviceUniqueBySn(sn));
                po.setDeviceName(iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                po.setOpenType(OpenTypeEnum.BY_VISTOR.getType());
                try {
                    po.setPassTime(DateUtil.formatStringToDate(qq.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                } catch (ParseException e) {
                    LOG.error("云对讲pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                }
                po.setUploadTime(new Date());
                po.setRoomNum(qq.getRoomNum());
                po.setQqNum(iCloudIntercomDeviceServiceDao.getQqNumByTinyIdAndProjectId(qq.getTinyId(),po.getProjectId()));
                po.setIsOpen(qq.getIsOpen());
                po.setBeginVisitTime(DateUtil.formatStringToDate(qq.getBeginVisitTime(),DateUtil.DATE_FORMAT_TYPE1));
                po.setEndVisitTime(DateUtil.formatStringToDate(qq.getEndVisitTime(),DateUtil.DATE_FORMAT_TYPE1));
                po.setSynchro(0);
                po.setStatus(DataStatusEnum.NORMAL.getType());
                po.setCreateTime(new Date());
                res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
            }
        }else if(type == 3){
            //用户本人通行
            List<CloudTalkSelfDTO> selfs;
            try {
                selfs=(List<CloudTalkSelfDTO>)JsonUtil.toListObject(deviceRecordJson,ArrayList.class,CloudTalkSelfDTO.class);
            } catch (IOException e) {
                throw new Exception("云对讲pushDeviceRecord【云端接收设备端的通行记录】解析密码开门通行记录json失败",e);
            }
            for(CloudTalkSelfDTO self : selfs){
                TimeTaskDevicePassRecordPO po=new TimeTaskDevicePassRecordPO();
                po.setPdId(LogicIdUtil.bussinessId());
                po.setProjectId(StringHandlerUtil.getProjectIdBySn(sn));
                po.setDeviceType(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                po.setDeviceUnique(StringHandlerUtil.getDeviceUniqueBySn(sn));
                po.setDeviceName(iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(sn));
                po.setOpenType(type);
                try {
                    po.setPassTime(DateUtil.formatStringToDate(self.getOpenTime(), DateUtil.DATE_FORMAT_TYPE1));
                } catch (ParseException e) {
                    LOG.error("云对讲pushDeviceRecord【云端接收设备端的通行记录】通行时间为null",e);
                }
                po.setUploadTime(new Date());
                if(StringUtils.isBlank(self.getRoomNum())){
                    //根据QQ物联身份id及项目id查询房间号及楼栋单元号查询房间编号
                    iCloudIntercomDeviceServiceDao.getRoomNumBySn(self.getTinyId(),
                            po.getProjectId(),
                            StringHandlerUtil.getBuildNumBySn(sn),
                            StringHandlerUtil.getUnitBySn(sn));
                }else {
                    po.setRoomNum(self.getRoomNum());
                }
                po.setIsOpen(self.getIsOpen());
                po.setSynchro(0);
                po.setStatus(DataStatusEnum.NORMAL.getType());
                po.setCreateTime(new Date());
                res = iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
            }
        }
        return res;
    }

    /**
     * <desc>
     *      云端接收PAD人脸认证的通行记录
     * </desc>
     *
     * @param appUploadPassRecordDTO 通行记录信息
     * @return
     * @author Qiang.S
     * @createDate 2018/05/16
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer pushPadFaceRecord(AppUploadPassRecordDTO appUploadPassRecordDTO) throws Exception {
        TimeTaskDevicePassRecordPO po=new TimeTaskDevicePassRecordPO();
        po.setPdId(LogicIdUtil.bussinessId());
        //访客为2 其他为业主
        if (appUploadPassRecordDTO.getUserType() != null && "2".equals(appUploadPassRecordDTO.getUserType())) {
            po.setOpenType(OpenTypeEnum.BY_VISITOR_FACE.getType());
        }else {
            po.setOpenType(OpenTypeEnum.BY_FACE_RECOGNITION.getType());
        }
        po.setUserId(appUploadPassRecordDTO.getUId());
        po.setProjectId(appUploadPassRecordDTO.getProjectId());
        if ("1".equals(appUploadPassRecordDTO.getType())) {//梯控
            po.setDeviceType(PropertyEquipTypeEnum.CLOUD_PASS_RECORD_ELEVATOR.getType());
        }
        if ("2".equals(appUploadPassRecordDTO.getType())) {//门禁
            po.setDeviceType(PropertyEquipTypeEnum.ENTRANCE.getType());
        }
        po.setDeviceUnique(appUploadPassRecordDTO.getDeviceUnique());
        po.setDeviceName(appUploadPassRecordDTO.getDeviceName());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        po.setPassTime(formatter.parse(appUploadPassRecordDTO.getPassTime()));
        po.setUploadTime(formatter.parse(appUploadPassRecordDTO.getUploadTime()));
        po.setFacePicUrl(appUploadPassRecordDTO.getUploadFilePath());
        po.setIsOpen(0);
        po.setSynchro(0);
        po.setSource(4);
        po.setStatus(DataStatusEnum.NORMAL.getType());
        po.setCreateTime(new Date());
        return iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
    }

    /**
     * <desc>
     * 校验开门动态密码（校验成功后生成动态密码通行记录）
     * <desc/>
     *
     * @param checkDTO 动态密码信息
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-27
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Boolean checkDynamicPwd(CloudIntercomDynamicPwdCheckDTO checkDTO) throws Exception {
        String elapsedtime = "checkDynamicPwd【校验开门动态密码impl】开始执行：" + DateUtil.fomatDate1(new Date());

        try {
            elapsedtime += ";retrieve开始执行：" + DateUtil.fomatDate1(new Date());
            CloudIntercomDeviceCacheVO cacheVO = retrieve(checkDTO.getToken());

            AppVisitorPassCodeRecordPO passCode = null;
            //1.校验动态密码
            if (StringUtils.isBlank(checkDTO.getRoomId())){
                elapsedtime += ";getAppVisitorPassCode开始执行：" + DateUtil.fomatDate1(new Date());
                passCode = iCloudIntercomDeviceServiceDao.getAppVisitorPassCode(
                        cacheVO.getProjectId(), checkDTO.getDynamicPwd(),
                        cacheVO.getDeviceId()
                );
            }else {
                elapsedtime += ";getAppVisitorPassCodeByRoomId开始执行：" + DateUtil.fomatDate1(new Date());
                passCode = iCloudIntercomDeviceServiceDao.getAppVisitorPassCodeByRoomId(
                        cacheVO.getProjectId(), checkDTO.getDynamicPwd(),
                        cacheVO.getDeviceId(), checkDTO.getRoomId()
                );
                if(null == passCode){
                    //查询是否在本条访客信息有临时权限 如是则校验开门密码则不需要加房间参数,但需校验访客电梯临时权限的楼层号是否与传入的房间楼层号匹配
                    AppVisitorPassCodeRecordPO temAuth = iCloudIntercomDeviceServiceDao.getAppVisitorPassCodeByTemporaryAuth(cacheVO.getProjectId(), checkDTO.getDynamicPwd(), cacheVO.getDeviceId());
                    if(null != temAuth && StringUtils.isNotEmpty(temAuth.getTemporaryAuthDeviceUniques())){
                       elapsedtime += ";getAppVisitorPassCode开始执行：" + DateUtil.fomatDate1(new Date());
                       passCode = iCloudIntercomDeviceServiceDao.getAppVisitorPassCode(
                               cacheVO.getProjectId(), checkDTO.getDynamicPwd(),
                               cacheVO.getDeviceId()
                       );
                       if(passCode != null){
                           List<String> cloudTalkUnitList = iCloudIntercomDeviceServiceDao.getCloudIntercomUnit(checkDTO.getSn());
                           Map<String,Object> deviceMap = new HashMap<>();
                           if(StringUtils.isNotEmpty(passCode.getMainDoorElevatorAuth())){
                               Map<String,Object> mainDoorMap = JsonUtil.JsonToMap(passCode.getMainDoorElevatorAuth());
                               deviceMap.putAll(mainDoorMap);
                           }
                           if(StringUtils.isNotEmpty(passCode.getBackDoorElevatorAuth())){
                               Map<String,Object> backDoorMap = JsonUtil.JsonToMap(passCode.getBackDoorElevatorAuth());
                               deviceMap.putAll(backDoorMap);
                           }
                           int count = 0;
                           for(Map.Entry<String,Object> entry : deviceMap.entrySet()){
                               String deviceId = entry.getKey();
                               List<String> list= Arrays.asList(entry.getValue().toString().split(","));
                               List<String> elevatorUnitList = iCloudIntercomDeviceServiceDao.getElevatorUnit(deviceId,passCode.getProjectId());
                               for(String str : elevatorUnitList){
                                   if(cloudTalkUnitList.contains(str)&&list.contains(Integer.valueOf(checkDTO.getRoomNum().substring(0,2)).toString())){
                                       count++;
                                       break;
                                   }
                               }
                               if(count>0){
                                   break;
                               }
                           }
                           if(count==0){
                               passCode = null;
                           }
                       }
                    }

                }
            }
            if (null == passCode){
                return false;
            }
            boolean pushBlackList = false;
            //3.增加动态密码已使用次数
            if(iPropertyEquipDao.checkEquipMode(StringHandlerUtil.getDeviceUniqueBySn(checkDTO.getSn()),3) > 0) {
                QrcodePassUserInfoVO vo = iPropertyEquipDao.findRoomQrcodeInfoByPassId(passCode.getPassId());
                if (vo != null) {
                    //更新访客使用次数
                    if (vo.getChargeMode() != null && vo.getChargeMode() == 2
                            && vo.getRoomChargeMode() != null && vo.getRoomChargeMode() == 1 && vo.getUsableCount() <= 0) {
                        return false;
                    }
                    iPropertyEquipDao.udpateAppVisitorUseNum(vo.getUserId());
                    if (vo.getChargeMode() != null && vo.getChargeMode() == 2
                            && vo.getRoomChargeMode() != null && vo.getRoomChargeMode() == 1) {
                        //更新业主房间次数
                        if (StringUtils.isNotBlank(vo.getQrcodeBatchRecordId())) {
                            Integer row = iPropertyEquipDao.updateQrcodeRoomCount(vo.getQrcodeBatchRecordId(), vo.getUsableCount() > 1 ? 1 : 0);
                            if (row < 1 || vo.getUsableCount() == 1) {
                                //推送黑名单数据
                                pushBlackList = true;
                            }
                        }
                    }
                }
            }
            //安卓云对讲通行记录后台不生成由设备上传
            if ("1".equals(cacheVO.getSystemType())) {
                //2.生成动态密码通行记录
                TimeTaskDevicePassRecordPO po=new TimeTaskDevicePassRecordPO();
                po.setPdId(LogicIdUtil.bussinessId());
                po.setProjectId(StringHandlerUtil.getProjectIdBySn(checkDTO.getSn()));
                po.setDeviceType(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType());
                po.setDeviceUnique(StringHandlerUtil.getDeviceUniqueBySn(checkDTO.getSn()));

                elapsedtime += ";getDeviceCloudNameBySn开始执行：" + DateUtil.fomatDate1(new Date());
                po.setDeviceName(iCloudIntercomDeviceServiceDao.getDeviceCloudNameBySn(checkDTO.getSn()));
                po.setOpenType(OpenTypeEnum.BY_DYNAMIC_PASSWORD.getType());
                po.setRoomNum(checkDTO.getRoomNum());
                if (StringUtils.isBlank(checkDTO.getRoomNum())){
                    elapsedtime += ";getAppUserRoomByUserId开始执行：" + DateUtil.fomatDate1(new Date());
                    //获取房间信息
                    AppUserRoomPO roomPO = iCloudIntercomDeviceServiceDao.getAppUserRoomByUserId(
                            passCode.getProjectId(),
                            passCode.getUserId(),
                            cacheVO.getDeviceUnique(),
                            cacheVO.getSmartType()
                    );
                    po.setRoomNum(roomPO != null ? roomPO.getRoomNum() : checkDTO.getRoomNum());
                }
                po.setPassTime(new Date());
                po.setUploadTime(new Date());
                po.setIsOpen(0);
                po.setSynchro(0);
                po.setDynamicPassword(checkDTO.getDynamicPwd());
                po.setSource(5);
                po.setStatus(DataStatusEnum.NORMAL.getType());
                po.setCreateTime(new Date());
                elapsedtime += ";iAppDevicePassRecordDao.save开始执行：" + DateUtil.fomatDate1(new Date());
                iAppDevicePassRecordDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
            }

            elapsedtime += ";increaseAppVisitorPassCodeUsedNum开始执行：" + DateUtil.fomatDate1(new Date());
            if(pushBlackList){
                String projectId = StringHandlerUtil.getProjectIdBySn(checkDTO.getSn());
                //推送数据
                //推送黑名单更新数据
                List<DeviceBusinessChangeLogPO> changes = new ArrayList<>();
                List<DeviceBusinessElevatorChangeLogPO> elevatorChanges = new ArrayList<>();
                List<DeviceBusinessEntranceChangeLogPO> entranceChanges = new ArrayList<>();
                Map<String,Object> blackList = new HashMap<>();
                blackList.put("projectId", projectId);
                blackList.put("roomId", passCode.getRoomId());
                blackList.put("version",0);
                DeviceBusinessChangeLogPO talkPO = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_BLACK_LIST, JsonUtil.toJSON(blackList), projectId);
                changes.add(talkPO);
                DeviceBusinessElevatorChangeLogPO elevatorPo = new DeviceBusinessElevatorChangeLogPO(projectId, CloudElevatorChangeBusinessEnum.PUSH_BLACK_LIST, JsonUtil.toJSON(blackList));
                elevatorChanges.add(elevatorPo);
                DeviceBusinessEntranceChangeLogPO entrancePO = new DeviceBusinessEntranceChangeLogPO(projectId, CloudEntranceChangeBusinessEnum.PUSH_BLACK_LIST, JsonUtil.toJSON(blackList));
                entranceChanges.add(entrancePO);
                JSONObject pushJs = new JSONObject();
                pushJs.put("data", changes);
                //发送云对讲业务指令
                messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE, JsonUtil.toJSON(pushJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE, RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);
                pushJs.put("data", elevatorChanges);
                //推送云电梯业务指令
                messageSender.send(
                        RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ELEVATOR_CHANGE_BUSINESS_QUEUE,
                        JsonUtil.toJSON(pushJs),
                        RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_CLOUD_ELEVATOR_CHANGE_BUSINESS_ROUTING_KEY);
                //发送云门禁业务指令
                pushJs.put("data", entranceChanges);
                messageSender.send(
                        RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                        JSON.toJSONString(pushJs),
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                        RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
                );
            }
            return true;
        } finally {
            elapsedtime += ";checkDynamicPwd【校验开门动态密码impl】执行结束：" + DateUtil.fomatDate1(new Date());
            LOG.info(elapsedtime);
        }
    }


    /**
     * <desc>
     *      获取云对讲设备服务权限信息
     * <desc/>
     *
     * @param getDTO 获取云对讲服务权限DTO
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-16
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<CloudIntercomDeviceAuthVO.Room> getDeviceServeRoomsByPage(CloudIntercomDeviceAuthGetDTO getDTO) throws Exception {
        String elapsedtime = "getDeviceServeRoomsByPage【分页获取设备服务房间impl】开始执行：" + DateUtil.fomatDate1(new Date());
        try {
            elapsedtime += ";retrieve开始执行：" + DateUtil.fomatDate1(new Date());
            //从缓存获取云对讲设备信息对象
            CloudIntercomDeviceCacheVO cacheVO = retrieve(getDTO.getToken());

            Page<CloudIntercomDeviceAuthVO.Room> page = new Page<>();
            //1.分页获取云对讲服务的房间列表
            page.getPage().setCurrentPage(getDTO.getPage().toString());
            page.getPage().setPageSize(getDTO.getPageSize().toString());

            elapsedtime +=";getServeRoomsPage开始执行：" + DateUtil.fomatDate1(new Date());
            List<CloudIntercomDeviceAuthVO.Room> rooms =
                    iCloudIntercomDeviceServiceDao.getServeRoomsPage(
                            cacheVO.getDeviceUnique(),
                            StringHandlerUtil.getProjectIdByDeviceUnique(cacheVO.getDeviceUnique()),
                            cacheVO.getSmartType(),
                            page.getPage().getStartSlip(), page.getPage().getPageSize());

            elapsedtime += ";getServeRoomsCount开始执行：" + DateUtil.fomatDate1(new Date());
            Integer count = iCloudIntercomDeviceServiceDao.getServeRoomsCount(
                    cacheVO.getDeviceUnique(),
                    StringHandlerUtil.getProjectIdByDeviceUnique(cacheVO.getDeviceUnique()),
                    cacheVO.getSmartType()
            );
            //填充返回数据集
            page.setRows(rooms, count);
            return page;
        } finally {
            elapsedtime += ";getDeviceServeRoomsByPage【分页获取设备服务房间impl】执行结束：" + DateUtil.fomatDate1(new Date());
            LOG.info(elapsedtime);
        }
    }

    /**
     * <desc>
     * 获取房间下的住户信息
     * <desc/>
     *
     * @param roomIds 房间id
     * @return
     * @author Chunjian.G
     * @createDate 2018-01-29
     */
    @Override
    public List<CloudIntercomDeviceAuthVO.RoomUser> getUsersByRoomIds(String roomIds,String sn) throws Exception {
        String[] idArr = StringHandlerUtil.splitString(roomIds);
        if (idArr.length == 0){
            return null;
        }
        //根据sn查询该设备是Linux还是Andriod设备
        Integer count = iCloudIntercomDeviceServiceDao.getDeviceType(sn);
        List<CloudIntercomDeviceAuthVO.RoomUser> roomUsers =
                iCloudIntercomDeviceServiceDao.getUsersByRoomIds(idArr);
        for(CloudIntercomDeviceAuthVO.RoomUser room : roomUsers){
            room.setIsOnline(1);
            //如果是Andriod设备，则查询出该用户的灵云clientUserId
            if(count>0){
                room.setSipAccount(iCloudIntercomDeviceServiceDao.getLykzUserId(room.getUserId()));
            }
        }
        return roomUsers;
    }


    /**
     * <desc>
     * 获取云对讲设备附加信息
     * <desc/>
     *
     * @param deviceUnique 云对讲设备唯一码
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-20
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public CloudIntercomOtherInfoVO getDeviceOtherInfo(String deviceUnique) throws Exception {
        CloudIntercomOtherInfoVO otherInfoVO = iCloudIntercomDeviceServiceDao.getDeviceOtherInfo(deviceUnique);
        return otherInfoVO;
    }


    /**
     * <desc>
     * 获取云对讲设备多媒体展示信息
     * <desc/>
     *
     * @param getDTO 多媒体展示信息获取条件
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<CloudIntercomMediaVO> getDeviceMedias(CloudIntercomMediaGetDTO getDTO) throws Exception {

        if (getDTO.getDeviceUnique() != null) {
            String screenType = iCloudIntercomDeviceServiceDao.getScreenTypeByDeviceUnique(getDTO.getDeviceUnique());
            //门口机
            List<CloudIntercomMediaVO> mediaVOS = iCloudIntercomDeviceServiceDao.getDeviceMedias(
                    getDTO.getDeviceUnique(),
                    StringHandlerUtil.getProjectIdByDeviceUnique(getDTO.getDeviceUnique()),
                    Integer.parseInt(getDTO.getDeviceType()),
                    getDTO.getMediaType(),
                    getDTO.getPageSize()
            );
            if (screenType == null || screenType.equals(ScreenTypeEnum.SEVEN_SCREEN_CLOUD_INTERCOM.getType())){
                mediaVOS.forEach(cloudIntercomMediaVO -> {
                    if (StringUtils.isNotBlank(cloudIntercomMediaVO.getAttacheFileUrl())){
                        cloudIntercomMediaVO.setAttacheFileUrl(cloudIntercomMediaVO.getAttacheFileUrl().replaceAll("https", "http"));
                    }
                });
            }
            return mediaVOS;
        } else {
            //从缓存获取云对讲设备信息对象
            CloudIntercomDeviceCacheVO cacheVO = retrieve(getDTO.getToken());
            String screenType = iCloudIntercomDeviceServiceDao.getScreenTypeByDeviceUnique(getDTO.getDeviceUnique());
            //门口机
            List<CloudIntercomMediaVO> mediaVOS = iCloudIntercomDeviceServiceDao.getDeviceMedias(
                    cacheVO.getDeviceUnique(),
                    cacheVO.getProjectId(),
                    CloudIntercomTypeEnum.GATE.getType(),
                    getDTO.getMediaType(),
                    getDTO.getPageSize()
            );
            //围墙机
            List<CloudIntercomMediaVO> walls = iCloudIntercomDeviceServiceDao.getDeviceMedias(
                    cacheVO.getDeviceUnique(),
                    cacheVO.getProjectId(),
                    CloudIntercomTypeEnum.WALL.getType(),
                    getDTO.getMediaType(),
                    getDTO.getPageSize()
            );

            mediaVOS.addAll(walls);
            if (screenType == null || screenType.equals(ScreenTypeEnum.SEVEN_SCREEN_CLOUD_INTERCOM.getType())){
                mediaVOS.forEach(cloudIntercomMediaVO -> {
                    if (StringUtils.isNotBlank(cloudIntercomMediaVO.getAttacheFileUrl())){
                        cloudIntercomMediaVO.setAttacheFileUrl(cloudIntercomMediaVO.getAttacheFileUrl().replaceAll("https", "http"));
                    }
                });
            }
            return mediaVOS;
        }
    }

    /**
     * <desc>
     * 获取云对讲设备状态（1:可用  2:禁用）
     * <desc/>
     *
     * @param sn
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-23
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer getDeviceState(String sn) throws Exception {
        return iCloudIntercomDeviceServiceDao.getDeviceState(sn);
    }

    /**
     * <desc>
     * 获取云对讲设备二维码
     * <desc/>
     *
     * @param sn
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-23
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public String getDeviceQrcodeUrl(String sn) throws Exception {
        return iCloudIntercomDeviceServiceDao.getDeviceQrcodeUrl(sn);
    }

    /**
     * <desc>
     * 获取云对讲轮询命令
     * <desc/>
     *
     * @param getDTO 分页参数
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-25
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<CloudIntercomChangeLogOrderVO> getDeviceChangeLogOrders(CloudIntercomChangeLogGetDTO getDTO) throws Exception {
        String elapsedtime = "getDeviceChangeLogOrders【分页获取云对讲轮询命令impl】开始执行：" + DateUtil.fomatDate1(new Date());
        //将DTO转换为Map params
        Map<String, Object> selectParams = SqlUtil.convertBeanToMapParams(getDTO);
        //1.分页获取待处理命令
        Page<CloudIntercomChangeLogOrderVO> page = new Page<>();
        page.getPage().setCurrentPage(getDTO.getPage().toString());
        page.getPage().setPageSize(getDTO.getPageSize().toString());
        selectParams.put("currentPage",page.getPage().getStartSlip());
        selectParams.put("pageSize",page.getPage().getPageSize());
        elapsedtime += ";getDeviceChangeLogOrders开始执行：" + DateUtil.fomatDate1(new Date());
        List<CloudIntercomChangeLogOrderVO> orderVOS =
                iCloudIntercomDeviceServiceDao.getDeviceChangeLogOrders(selectParams);

        Integer count = iCloudIntercomDeviceServiceDao.getDeviceChangeLogOrdersCount(getDTO.getSn());
        //填充返回数据集
        page.setRows(orderVOS, count);

        //2.对命令做后续处理
        if (null != orderVOS && !orderVOS.isEmpty()){
            //a.将commandData转换为JSONObject
            for (CloudIntercomChangeLogOrderVO orderVO: orderVOS){
                //全量更新时，commandData不是json格式
                if (orderVO.getCommandData() != null &&
                        !PushCloudIntercomChangeEnum.PUSH_FULL.getType().toString().equals(orderVO.getCommandType())){
                    orderVO.setCommandData(JSON.parse(orderVO.getCommandData().toString()));
                }
            }
            //b.将命令标记为处理中
            String[] idArr = new String[orderVOS.size()];
            for (int i = 0; i< idArr.length; i++){
                idArr[i] = orderVOS.get(i).getId();
            }
            iCloudIntercomDeviceServiceDao.changeChangeLogOrdersStatus(getDTO.getSn(), idArr, 1);
        }
        return page;
    }

    /**
     * <desc>
     * 云对讲设备批量完成轮询命名
     * <desc/>
     *
     * @param ids 轮询命令，多个以英文逗号拼接
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-25
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer finishChangeLogOrders(String sn, String ids) throws Exception {
        String[] idArr = StringHandlerUtil.splitString(ids);
        return iCloudIntercomDeviceServiceDao.changeChangeLogOrdersStatus(sn, idArr, 2);
    }

    /**
     * <desc>
     * 同一项目下，根据userSip获取手机号
     * <desc/>
     *
     * @param projectId 项目编号
     * @param userSips  用户sip，多个以英文逗号拼接
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-25
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<String> getPhoneNoByUserSips(String projectId, String userSips) throws Exception {
        String elapsedtime = "getPhoneNoByUserSips【根据userSip获取手机号impl】开始执行：" + DateUtil.fomatDate1(new Date());
        try {
            String[] sipArr = StringHandlerUtil.splitString(userSips);
            return iCloudIntercomDeviceServiceDao.getPhoneNoByUserSips(projectId, sipArr);
        } finally {
            elapsedtime += ";getPhoneNoByUserSips【根据userSip获取手机号impl】执行结束" + DateUtil.fomatDate1(new Date());
            LOG.info(elapsedtime);
        }
    }

    /**
     * <desc>
     * 检查用户是否有权限
     * <desc/>
     *
     * @param sn
     * @param tinyId qq物联id
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-27
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Boolean checkUserByTinyId(String sn, String tinyId) throws Exception {
        Integer smartType = iCloudIntercomDeviceServiceDao.getSmartTypeBySn(sn);
        if (null == smartType){
            return false;
        }
        AppUserRoomPO roomPO = iCloudIntercomDeviceServiceDao.getAppUserRoomByTinyId(
                StringHandlerUtil.getProjectIdBySn(sn),
                tinyId,
                StringHandlerUtil.getDeviceUniqueBySn(sn),
                smartType
        );
        if (null == roomPO){
            return false;
        }
        return true;
    }

    /**
     * <desc>
     *      获取云对讲人脸识别配置信息
     * </desc>
     *
     * @param sn
     * @return
     * @author Jiaqi.X
     * @createDate 2018/05/21
     */
    public CloudTalkFaceApplyInfoVO pullDeviceInfo(String sn){
        CloudTalkFaceApplyInfoVO vo = iCloudIntercomDeviceServiceDao.pullDeviceInfo(StringHandlerUtil.getProjectIdBySn(sn));
        if(vo!=null) {
            vo.setGroupId("itlong");
            if ("0".equals(vo.getLivenessControl())) {vo.setLivenessControl("LOW");}
            if ("1".equals(vo.getLivenessControl())) {vo.setLivenessControl("NORMAL");}
            if ("2".equals(vo.getLivenessControl())) {vo.setLivenessControl("HIGH");}
            if ("3".equals(vo.getLivenessControl())) {vo.setLivenessControl("NONE");}
            vo.setQualityControl("NONE");
            if(iCloudIntercomDeviceServiceDao.getFaceStatus(StringHandlerUtil.getProjectIdBySn(sn)).equals("1")){
                vo.setEnable(iCloudIntercomDeviceServiceDao.getDeviceFaceStatus(sn).equals("0") ? false : true );
            }else{
                vo.setEnable(false);
            }
        }else{
            vo = new CloudTalkFaceApplyInfoVO();
            vo.setEnable(false);
        }
        return vo;
    }

    /**
     * <desc>
     *      获取云对讲iot信息
     * </desc>
     *
     * @param sn
     * @return
     * @author Qiang.S
     * @createDate 2019/07/16
     */
    public CloudTalkIotInfoVO getCloudTalkIotInfo(String sn){
        return iCloudIntercomDeviceServiceDao.getCloudTalkIotInfo(sn);
    }

    /**
     * <desc>
     *      根据SN号获取设备待机界面图片
     * <desc/>
     *
     * @param sn
     * @return
     * @author Juguang.S
     * @createDate 2018-08-09
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public String getStandbyInterfacePicture(String sn) {
        return iCloudIntercomDeviceServiceDao.getStandbyInterfacePicture(sn);
    }

    /**
     * <desc>
     *      云对讲上报设备的能力集信息
     * <desc/>
     *
     * @param sn
     * @param capacitySet 表示设备支持哪些功能，有哪些能力 json String数据
     * @return
     * @author Juguang.S
     * @createDate 2018-08-09
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void reportCapacitySet(String capacitySet, String sn) {
        JSONObject capacitySetObject = (JSONObject) JSONObject.parse(capacitySet);
        /*capacitySet = capcityObject.getString("capacitySet");
        JSONObject capacitySetObject =  JSONObject.parseObject(capacitySet);*/

        String version = capacitySetObject.getString("version");
        String deviceAttributes = capacitySetObject.getString("deviceAttributes");
        String mac = capacitySetObject.getString("mac");
        String cmdList = capacitySetObject.getString("cmdList");
        JSONObject versionObject =  JSONObject.parseObject(version);
        String screen = capacitySetObject.getString("screen");
        JSONObject screenObject =  JSONObject.parseObject(screen);
        String other = capacitySetObject.getString("other");
        JSONObject otherObject =  JSONObject.parseObject(other);

        String firmware = versionObject.getString("firmware");
        String mcu = versionObject.getString("mcu");
        String apk = versionObject.getString("apk");
        String linuxAppVer =  versionObject.getString("linuxAppVer");
        Boolean hasScreen = screenObject.getBoolean("hasScreen");
        String size = screenObject.getString("size");
        Boolean standbyPic = otherObject.getBoolean("standbyPic");
        String   productCode  =   iCloudIntercomDeviceServiceDao.getProductCode(deviceAttributes);
        //拼接map参数
        Map<String,Object>  map  = new  HashMap<String,Object>();
        map.put("hasScreen",hasScreen==true?1:0);
        map.put("size",size);
        map.put("firmware",firmware);
        map.put("mcu",mcu);
        map.put("sn",sn);
        map.put("apk",apk);
        map.put("standbyPic",standbyPic==true?1:0);
        map.put("linuxAppVer",linuxAppVer);
        map.put("deviceAttributes",deviceAttributes);
        map.put("mac",mac);
        map.put("cmdList",cmdList);
        map.put("productCode",productCode);
        iCloudIntercomDeviceServiceDao.updateDeviceInfo(map);
    }

    /**
     * <desc>
     *      获取云对讲设备更新信息
     * </desc>
     *
     * @param sn
     * @param filePackage 安装文件 包名
     * @param versionCode 安装文件 版本号
     * @param deviceType 软件类型 0安卓APK程序，1安卓系统固件，2按键单片机固件
     * @return
     * @author Qiang.S
     * @createDate 2018/08/30
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public CloudDeviceUpdateInfoVO deviceIntercomUpdate(String sn,String filePackage,String versionCode,String deviceType) {
        //根据sn,更新文件包名,版本号,软件类型 查找更新文件下载路径以及指令ID
        List<CloudIntercomChangeLogOrderVO> list = iCloudIntercomDeviceServiceDao.getUpdateDeviceInfo(sn);
        if (list==null || list.size() == 0) {//无此设备升级命令
            return null;
        }
        StringBuffer ids = new StringBuffer();
        //取消所有沉余指令
        for (int i=1;i<list.size();i++) {
            ids.append(list.get(i).getId().toString()+",");
        }
        String[] id = ids.toString().split(",");

        OperateUpdateDetailVO operateUpdateDetailVO = iOperatePackageDao.getUpdateDetailForDeviceUpdate(list.get(0).getCommandData().toString(),filePackage,deviceType,"1");
        if (operateUpdateDetailVO == null) {
            return null;
        }
        CloudDeviceUpdateInfoVO cloudDeviceUpdateInfoVO = new CloudDeviceUpdateInfoVO();
        cloudDeviceUpdateInfoVO.setCommandId(list.get(0).getId().toString());
        cloudDeviceUpdateInfoVO.setFileName(operateUpdateDetailVO.getUpdateName());
        cloudDeviceUpdateInfoVO.setMd5(operateUpdateDetailVO.getMd5());
        cloudDeviceUpdateInfoVO.setVersionCode(operateUpdateDetailVO.getVersion());
        cloudDeviceUpdateInfoVO.setUrl(operateUpdateDetailVO.getUpdateUrl());

        //将所有沉余指令清除
        iCloudIntercomDeviceServiceDao.changeChangeLogOrdersStatus(sn,id,2);
        //将执行的指令调整为 处理中
        String[] newId = {list.get(0).getId().toString()};
        iCloudIntercomDeviceServiceDao.changeChangeLogOrdersStatus(sn,newId,1);
        return cloudDeviceUpdateInfoVO;
    }

    /**
     * <desc>
     *      根据roomId projectId判定该房间下的业主是否被冻结
     * </desc>
     *
     * @param roomId 房间ID
     * @param projectId 项目ID
     * @return
     * @author Juguang.S
     * @createDate 2018/11/22
     */
    @Override
    public Integer getUserStatusProject(String roomId,String projectId){
        return iCloudIntercomDeviceServiceDao.getUserStatusProject(roomId,projectId);
    }

    /**
     * <desc>
     *      获取单元代号
     * </desc>
     *
     * @param sn
     * @return
     * @author Jiaqi.x
     * @createDate 2018/11/27
     */
    @Override
    public List<Map<String,Object>> getUnitAlias(String sn){
        return iCloudIntercomDeviceServiceDao.getUnitAlias(StringHandlerUtil.getProjectIdBySn(sn),sn);
    }

    /**
     * <desc>
     *      通过百度id来校验该百度Id是否未绑定过百度授权码
     * <desc/>
     *
     * @param baiduId 百度指纹码
     * @return
     * @author Juguang.S
     * @createDate 2019/03/12
     */
    @Override
    public Integer getBaiduIdBingStatus(String baiduId) {
        return iCloudIntercomDeviceServiceDao.getBaiduIdBingStatus(baiduId);
    }

    /**
     * <desc>
     *      根据deviceUnique查询该设备是否已绑定或已购买
     * <desc/>
     *
     * @param deviceUnique 设备唯一码
     * @return
     * @author Juguang.S
     * @createDate 2019/03/12
     */
    @Override
    public Integer getDeviceBuyOrBingStatus(String deviceUnique) {
        return iCloudIntercomDeviceServiceDao.getDeviceBuyOrBingStatus(deviceUnique);
    }

     /**
     * <desc>
     *      根据设备编号获取访客信息
     * </desc>
     *
     * @param deviceUnique 设备唯一码
     * @param smartType 云对讲类型，31-门口机，32-围墙机
     * @return
     * @author Qiang.S
     * @createDate 2019/02/28
     */
    @Override
    public List<CloudIntercomVisitorVO> getVisitorInfoByUnique(String deviceUnique, Integer smartType){
        return iCloudIntercomDeviceServiceDao.getVisitorInfoByUnique(deviceUnique, smartType);
    }
    
    /**
     * <desc>
     *      云对讲iot开门
     * </desc>
     *
     * @param userId 用户编号
     * @param sipAccount sip帐号
     * @param message 指令相关信息
     * @param timeout 开门时长
     * @return
     * @author Qiang.S
     * @createDate 2019/07/16
     */
    @Override
    public void iotOpenDoor(String userId, String sipAccount, String message, String timeout) {
        String deviceUnique = null;
        try {
            LOG.info("userId:" + userId);
            LOG.info("sipAccount:" + sipAccount);
            CloudIntercomDeviceVO intercomDevice = iCloudIntercomDeviceServiceDao.getDeviceUniqueBySip(sipAccount);
            String systemType = null;
            if (sipAccount.length() == 13) {
                deviceUnique = sipAccount;
                systemType = iCloudIntercomDeviceServiceDao.getSystemTypeByDeviceUnique(sipAccount);
            }else if (intercomDevice != null){
                deviceUnique = intercomDevice.getDeviceUnique();
                systemType = intercomDevice.getSystemType();
            }
            String productKey = iCloudIntercomDeviceServiceDao.getDeviceProductKey(deviceUnique);
            String[] detail = message.split("-");
            LOG.info("message:" + message);
            LOG.info("detail.length:" + detail.length);
            if (detail.length >= 3) {
                List<String> list = new ArrayList<>();
                for (int y = 3; y < detail.length; y++) {
                    list.add(detail[y]);
                }
                //LOG.info("list:" + list);

                List<Map<String, Object>> messages = new ArrayList<>();
                Map<String, Object> messageMap = new HashMap<>();
                messageMap.put("productKey", productKey);
                messageMap.put("topic", "/" + deviceUnique + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl());
                IotPubMessageDTO dto = new IotPubMessageDTO();
                dto.setSourceForm("itlong");
                dto.setCmd("1003");
                dto.setSnr(1);
                Map<String, Object> data = new HashMap<>();
                data.put("cmdVer", "0");
                if (detail[1].equals("idle")) {//空闲时开门
                    data.put("openType", "1");
                }
                if (detail[1].equals("spy")) {//主动呼出被接听开门
                    data.put("openType", "3");
                }
                if (detail[1].equals("talk")) {//对方呼自己开门
                    data.put("openType", "2");
                }
                data.put("numOfRoom", detail[2]);
                data.put("rooms", list);
                data.put("timeout", timeout);
                if ("2".equals(systemType)) {
                    data.put("userId", userId);//安卓云对讲的时候传user_id
                }
                dto.setData(data);
                messageMap.put("message", JsonUtil.toJSON(dto));
                messages.add(messageMap);
                this.sendCloudEntranceMessage(messages);
            }
        } catch (Exception e) {
            LOG.error("云对讲iot开门", e);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String message = "squirrelunlock-idle-0-";
        String[] detail = message.split("-");
        if (detail.length >= 3) {
            List<String> list = new ArrayList<>();
            for (int y = 3; y < detail.length; y++) {
                list.add(detail[y]);
            }
            System.out.println(1);
        }
        System.out.println(1);
    }

    /**
     * <desc>
     *      云对讲iot音视频切换
     * </desc>
     *
     * @param sipAccount sip帐号
     * @param message 指令相关信息
     * @return
     * @author Qiang.S
     * @createDate 2019/07/16
     */
    @Override
    public void switchVideo(String sipAccount, String message) {
        String deviceUnique = null;
        try {
            CloudIntercomDeviceVO intercomDevice = iCloudIntercomDeviceServiceDao.getDeviceUniqueBySip(sipAccount);
            String productKey = iCloudIntercomDeviceServiceDao.getDeviceProductKey(intercomDevice.getDeviceUnique());
            if (sipAccount.length() == 13) {
                deviceUnique = sipAccount;
            }else if (intercomDevice != null){
                deviceUnique = intercomDevice.getDeviceUnique();
            }
                List<Map<String, Object>> messages = new ArrayList<>();
                Map<String, Object> messageMap = new HashMap<>();
                messageMap.put("productKey", productKey);
                messageMap.put("topic", "/" + deviceUnique + "/user" + IotCloudCtrlInstructEnum.DEVICECMD.getUrl());
                IotPubMessageDTO dto = new IotPubMessageDTO();
                dto.setSourceForm("itlong");
                dto.setCmd("1001");
                dto.setSnr(1);
                Map<String, Object> data = new HashMap<>();
                data.put("cmdVer", "0");
                data.put("videoState",message);
                dto.setData(data);
                messageMap.put("message", JsonUtil.toJSON(dto));
                messages.add(messageMap);
                this.sendCloudEntranceMessage(messages);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <desc>
     *      根据sip帐号获取设备编号云对讲
     * </desc>
     *
     * @param sipAccount sip帐号
     * @return
     * @author Qiang.S
     * @createDate 2019/07/22
     */
    @Override
    public String getDeviceUniqueBySip(String sipAccount) {
        String deviceUnique = null;
        CloudIntercomDeviceVO intercomDevice = iCloudIntercomDeviceServiceDao.getDeviceUniqueBySip(sipAccount);
        if (sipAccount.length() == 13) {
            deviceUnique = sipAccount;
        }else if (intercomDevice != null){
            deviceUnique = intercomDevice.getDeviceUnique();
        }
        return deviceUnique;
    }

    /**
     * <desc>
     *      发布消息到iot中心
     * </desc>
     *
     * @param messages
     * @author Jiaqi.X
     * @createDate 2019/02/27
     */
    private void sendCloudEntranceMessage(List<Map<String,Object>> messages) throws Exception {
        if(!messages.isEmpty()){
            Map<String,Object> params = new HashMap<>();
            params.put("deviceOperateIotType", DeviceIotEnum.PUB_MESSAGE.getCommandType());
            params.put("devices",messages);
            JSONObject obj = new JSONObject();
            obj.put("data",params);
            messageSender.send(RabbitMQConstant.RABBITMQ_IOT_PUB_QUEUE, obj.toJSONString(),
                    RabbitMQConstant.RABBITMQ_IOT_PUB_EXCHANGE, RabbitMQConstant.RABBITMQ_IOT_PUB_KEY);
        }
    }


    /**
     * <desc>
     *      创建灵云设备账号信息 后续云对讲SDK本会改进传入appid创建相对应用下的设备账号
     * </desc>
     *
     * @return
     * @author Juguang.S
     * @createDate 2018/12/19
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public CloudIntercomAccountInfoPO createLykzDeviceAccount(String lykzAppid) throws Exception {
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime = sd.format(new Date());
        String sigParameter = Md5EncryptUtil.md5(String.format("%s%s%s",LYKZ_ACCOUNT_SID,LYKZ_ACCOUNT_TOKEN,nowTime)).toUpperCase();
        String url = "http://"+LYKZ_URL+":"+LYKZ_PORT+"/ucsrtc-rest-api/"+LYKZ_SOFT_VERSION+"/Accounts/"+LYKZ_ACCOUNT_SID+"/deviceClients?sig="+sigParameter;
        Map<String,Object> params = new HashMap<>();
        Map<String,String> map = new HashMap<>();
        map.put("appId",lykzAppid);
        params.put("client",map);
        String paramsStr = JSON.toJSONString(params);

        String responseStr = HttpProtocolUtil.httpPostByLykz(url,paramsStr,nowTime,LYKZ_ACCOUNT_SID);
        System.out.println("输出结果："+responseStr);

        if(StringUtils.isNotEmpty(responseStr)){
            Map<String, Object> jsonToMap = JsonUtil.JsonToMap(responseStr);
            if(jsonToMap != null && !jsonToMap.isEmpty()){
                Map<String, Object> jsonToMapResp = JsonUtil.JsonToMap(jsonToMap.get("resp").toString());
                if(jsonToMapResp != null && !jsonToMapResp.isEmpty()){
                    String respCode = jsonToMapResp.get("respCode").toString();
                    if(respCode.equals("000000")){
                        Map<String, Object> clientResp = JsonUtil.JsonToMap(jsonToMapResp.get("client").toString());
                        String clientNumber = clientResp.get("clientNumber").toString();
                        String clientPwd = clientResp.get("clientPwd").toString();
                        String loginToken = clientResp.get("loginToken").toString();
                        String userId = clientResp.get("userId").toString();

                        CloudIntercomAccountInfoPO infoPO = new CloudIntercomAccountInfoPO();
                        String lykzId = LogicIdUtil.bussinessId();
                        infoPO.setCloudIntercomAccountId(lykzId);
                        infoPO.setAccountType(2);
                        infoPO.setAccount(userId);
                        infoPO.setToken(loginToken);
                        infoPO.setClientPwd(clientPwd);
                        infoPO.setClientUserId(userId);
                        infoPO.setStatus(1);
                        infoPO.setAppid(lykzAppid);
                        infoPO.setBindingStatus(1);
                        infoPO.setCreateTime(new Date());
                        if(iCloudIntercomDeviceServiceDao.save(SqlUtil.durableData(infoPO, PlatformConstants.TABLE_SAVE))>0){
                            return infoPO;
                        }
                    }else{
                        return null;
                    }

                }
            }
        }
        return null;
    }

    /**
     * <desc>
     *      通过百度指纹码绑定百度识别码来完成离线人脸识别
     * <desc/>
     *
     * @param sn
     * @param baiduId 百度指纹码
     * @return
     * @author Juguang.S
     * @createDate 2019/02/26
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.NOT_SUPPORTED)
    public String getBaiduCode(String sn, String baiduId) throws Exception {
        //先判断该baiduId是否已绑定过百度识别授权码
        Map<String,Object> mapResult = iCloudIntercomDeviceServiceDao.getIsBingBaiduCode(baiduId);
        String projectId = StringHandlerUtil.getProjectIdBySn(sn);
        String deviceUnique = String.format("%s%s%04d",sn.substring(0,8),3,Integer.parseInt(sn.substring(sn.length()-3,sn.length())));
        if(null != mapResult){
            String oldProjectId = "";
            String oldDeviceUnique = "";
            if(mapResult.size()>2){
                oldProjectId = mapResult.get("projectId").toString();
                oldDeviceUnique = mapResult.get("deviceUnique").toString();
            }
            String baiduAuthCode = mapResult.get("baiduAuthCode").toString();
            String useStatus = mapResult.get("useStatus").toString();
            if(!projectId.equals(oldProjectId) || !deviceUnique.equals(oldDeviceUnique)){
                //处理设备坏了该BaiduId所绑定的激活码也不能正常使用，但后期又修好了，需1.释放该机号与之前所绑定百度id激活码之间的关系 2.将该激活码的状态改为已使用
                if(useStatus.equals("0") || iCloudIntercomDeviceServiceDao.getDeviceBuyOrBingStatus(deviceUnique)>0){
                    iCloudIntercomDeviceServiceDao.updateOldDeviceBingInfo(deviceUnique);
                    useStatus = "2";
                }
                //则需更新项目编号和设备唯一码
                iCloudIntercomDeviceServiceDao.updateProjectId(projectId,baiduId,deviceUnique,useStatus);
            }
            return baiduAuthCode;
        }
        Map<String,Object> mapInfo = null;
        //未绑定则查询未绑定的百度识别授权码完成绑定(绑定该设备购买时所绑定的激活码)
        Map<String,Object> map = iCloudIntercomDeviceServiceDao.getBaiduCode(deviceUnique);
        if(map == null || map.size() == 0){
            //判断是否由于百度识别授权码库存不足 若不是则将更新该设备的绑定关系
            mapInfo = iCloudIntercomDeviceServiceDao.isEnoughByBaiduCode();
            if(mapInfo == null || mapInfo.size() == 0){
                return "";
            }else{
                iCloudIntercomDeviceServiceDao.updateOldDeviceBingInfo(deviceUnique);
            }
        }
        DevicePadAuthCodePO devicePadAuthCodePO = new DevicePadAuthCodePO();
        if(mapInfo != null){
            devicePadAuthCodePO.setCodeId(mapInfo.get("codeId").toString());
            devicePadAuthCodePO.setBaiduAuthCode(mapInfo.get("baiduAuthCode").toString());
        }else{
            devicePadAuthCodePO.setCodeId(map.get("codeId").toString());
            devicePadAuthCodePO.setBaiduAuthCode(map.get("baiduAuthCode").toString());
        }
        devicePadAuthCodePO.setProjectId(projectId);
        devicePadAuthCodePO.setEmId(baiduId);
        devicePadAuthCodePO.setBaiduId(baiduId);
        devicePadAuthCodePO.setUseTime(new Date());
        devicePadAuthCodePO.setUseStatus(2);
        devicePadAuthCodePO.setUpdateTime(new Date());
        devicePadAuthCodePO.setDeviceUnique(deviceUnique);
        Map<String, Object> params = SqlUtil.durableData(devicePadAuthCodePO, PlatformConstants.TABLE_UPDATE);
        iCloudIntercomDeviceServiceDao.update(params);
        if(mapInfo != null){
            return mapInfo.get("baiduAuthCode").toString();
        }
        return map.get("baiduAuthCode").toString();
    }

    /**
     * <desc>
     *      获取云对讲
     * </desc>
     *
     * @param sn
     * @return
     * @author Jiaqi.X
     * @createDate 2019/09/11
     */
    public DeviceAuthTempPageVO<EntranceTempAuthVO> getTempAuths(String sn,String cPage,String pSize) throws Exception {
        String deviceUnique = StringHandlerUtil.getDeviceUniqueBySn(sn);
        //获取云对讲临时权限
        DeviceAuthTempPageVO<EntranceTempAuthVO> page = new DeviceAuthTempPageVO<>();
        int currentPage = StringUtils.isNotBlank(cPage) ? Integer.valueOf(cPage) : 1;
        int pageSize = StringUtils.isNotBlank(pSize) ? Integer.valueOf(pSize) : 20;
        int startPage = (currentPage-1)*pageSize;
        int endPage = (currentPage-1)*pageSize+pageSize;
        int count = 1;
        int haveNext = 0;
        //获取云对讲
        List<Map<String, Object>> auths = iCloudIntercomDeviceServiceDao.getTempAuths(Integer.valueOf(StringHandlerUtil.getDeviceIdByDeviceUnique(deviceUnique)),
                StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique));
        List<EntranceTempAuthVO> vos = new ArrayList<>();
        for (Map<String, Object> auth : auths) {
            if(count >= startPage && count<=endPage) {
                EntranceTempAuthVO tempVO = new EntranceTempAuthVO();
                tempVO.setUserId(StringHandlerUtil.getNullOrStringForObject(auth.get("userId")));
                tempVO.setUserName(StringHandlerUtil.getNullOrStringForObject(auth.get("userName")));
                tempVO.setIdcardKey(StringHandlerUtil.getNullOrStringForObject(auth.get("idcardKey")));
                tempVO.setVisitorType(auth.get("visitorType") != null ? Integer.valueOf(auth.get("visitorType").toString()) : null);
                tempVO.setIsLoss(StringHandlerUtil.getNullOrStringForObject(auth.get("isLoss")));
                //查询门禁地址
                Map<String, Object> address = iCloudIntercomDeviceServiceDao.getDeviceAddress(deviceUnique);
                //获取门禁地址下的电梯
                List<CloudElevatorVO> elevators = iCloudElevatorDao.getDeviceUniquesByEntranceAddress(address);
                //获取地址下电梯的临时权限
                Set<String> frontFloor = new HashSet<>();           //正门楼层
                Set<String> backFloor = new HashSet<>();            //背门楼层
                for (CloudElevatorVO elevator : elevators) {
                    //获取电梯的授权设备信息
                    List<AppElevatorAuthDTO> elevatorAuths = iCloudElevatorDao.getFloorAuth(auth.get("userId").toString(),
                            StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique), Integer.valueOf(elevator.getDeviceId()));
                    AppElevatorAuthVO tempElevatorAuth = StringHandlerUtil.convertElevatorAuth(elevatorAuths);
                    Optional<AppElevatorInfoVO> eAuth = tempElevatorAuth.getElevatorAuth().stream().filter(temp -> temp.getDeviceId().equals(elevator.getDeviceId())).findFirst();
                    if (eAuth.isPresent()) {
                        String[] floors = StringHandlerUtil.splitString(eAuth.get().getLiveFloor());
                        if(floors.length > 0){
                            String floorsStr = iCloudElevatorDao.getFloorNumByNaturalFloor(floors,StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique) + "1" + eAuth.get().getDeviceId());
                            floors = StringHandlerUtil.splitString(floorsStr);
                        }
                        for (String floor : floors) {
                            if (elevator.getLiftDoorType() == 1) {
                                frontFloor.add(floor);
                            } else {
                                backFloor.add(floor);
                            }
                        }
                    }
                }
                tempVO.setFrontFloor(String.join(",", frontFloor));
                tempVO.setBackFloor(String.join(",", backFloor));
                vos.add(tempVO);
            }else{
                haveNext = 1;
            }
            count++;
        }
        //获取访客
        List<DeviceTempVisitorVO> visitors = iDeviceEntranceInfoDao.getVisitors(deviceUnique);
        for(DeviceTempVisitorVO visitor : visitors){
            if(count >= startPage && count <= endPage) {
                EntranceTempAuthVO tempVO = new EntranceTempAuthVO();
                BeanUtils.copyProperties(visitor, tempVO);
                //查询门禁地址
                Map<String, Object> address = iCloudIntercomDeviceServiceDao.getDeviceAddress(deviceUnique);
                //获取门禁地址下的电梯
                List<CloudElevatorVO> elevators = iCloudElevatorDao.getDeviceUniquesByEntranceAddress(address);
                if (StringUtils.isNotBlank(visitor.getFrontElevatorAuth())) {
                    Map<String, Object> frontList = JsonUtil.toObject(visitor.getFrontElevatorAuth(), HashMap.class);
                    Set<String> fronts = new HashSet<>();
                    for (String key : frontList.keySet()) {
                        Optional<CloudElevatorVO> optional = elevators.stream().filter(elevator -> elevator.getDeviceId().equals(key)).findFirst();
                        if (optional.isPresent()) {
                            String[] floor = StringHandlerUtil.splitString(frontList.get(key).toString());
                            if(floor.length > 0){
                                String floors = iCloudElevatorDao.getFloorNumByNaturalFloor(floor,optional.get().getProjectId() + "1" + optional.get().getDeviceId());
                                floor = StringHandlerUtil.splitString(floors);
                            }
                            for (String f : floor) {
                                fronts.add(f);
                            }
                        }
                    }
                    tempVO.setFrontFloor(String.join(",", fronts));
                }
                if (StringUtils.isNotBlank(visitor.getBackElevatorAuth())) {
                    Map<String, Object> backList = JsonUtil.toObject(visitor.getBackElevatorAuth(), HashMap.class);
                    Set<String> backs = new HashSet<>();
                    for (String key : backList.keySet()) {
                        Optional<CloudElevatorVO> optional = elevators.stream().filter(elevator -> elevator.getDeviceId().equals(key)).findFirst();
                        if (optional.isPresent()) {
                            String[] floor = StringHandlerUtil.splitString(backList.get(key).toString());
                            if(floor.length > 0){
                                String floors = iCloudElevatorDao.getFloorNumByNaturalFloor(floor,optional.get().getProjectId() + "1" + optional.get().getDeviceId());
                                floor = StringHandlerUtil.splitString(floors);
                            }
                            for (String f : floor) {
                                backs.add(f);
                            }
                        }
                    }
                    tempVO.setBackFloor(String.join(",", backs));
                }
                vos.add(tempVO);
            }else{
                haveNext=1;
            }
            count++;
        }
        page.setDeviceAuthArr(vos);
        page.setTotal(count);
        page.setPage(currentPage);
        page.setCurrentTotal(pageSize);
        page.setHaveNext(haveNext);
        return page;
    }

    /**
     * <desc>
     *     通知云端升级失败原因
     * </desc>
     *
     * @param sn
     * @param id 轮询命令
     * @param msg 失败原因
     * @return 受影响的行数
     * @throws Exception
     * @author Qiang.S
     * @createDate 2019-08-12
     */
    @Override
    public Integer reportUpdateResult(String sn, String id, String msg) throws Exception {
        return iCloudIntercomDeviceServiceDao.reportUpdateResult(sn, id, 3,msg);
    }

    /**
     * <desc>
     *      根据sn获取该设备所对应批次号的云服务过期时间
     * </desc>
     *
     * @param sn
     * @return
     * @author Juguang.S
     * @createDate 2019/11/26
     */
    @Override
    public String getEndTimeBySn(String sn){
        String endTime = iCloudIntercomDeviceServiceDao.getEndTimeBySn(sn);
        if(StringUtils.isEmpty(endTime)){
            //需要排除的旧批次号集合
            List<String> oldBatchNumberArr = new ArrayList<>();
            //查询出需排除的旧批次集合
            List<String> oldBatchNumberList = iAppDeviceDao.getOldBatchNumberByProjectId(sn.substring(0,8));
            for(String oldBatchNumbers : oldBatchNumberList){
                for(String oldBatchNumber : oldBatchNumbers.split(",")){
                    oldBatchNumberArr.add(oldBatchNumber);
                }
            }
            //获取项目下最近批次号过期时间
            String endTimeByProjectId = iAppDeviceDao.getBatchNumberEndTimeByProjectId(sn.substring(0,8),oldBatchNumberArr.size()>0?oldBatchNumberArr:null);
            if(StringUtils.isNotEmpty(endTimeByProjectId)){
                return endTimeByProjectId;
            }else{
                return  "";
            }
        }else{
            return endTime;
        }

    }

    /**
     * <desc>
     * 获取云对讲地址信息
     * </desc>
     *
     * @param deviceUnique
     * @return
     * @author Jiaqi.X
     * @createDate 2019/10/14
     */
    @Override
    public Map<String, Object> getAddressByDeviceUnique(String deviceUnique) {
        return iCloudIntercomDeviceServiceDao.getAddressByDeviceUnique(deviceUnique);
    }

    /**
     * <desc>
     * 获取单元id
     * </desc>
     *
     * @param roomId
     * @Author chengshican
     * @Date 2020-12-08 13:51
     * @Param
     * @Return
     * @Exception
     */
    @Override
    public RoomInfoPO getUnitIdByRoomInfoId(String roomId) {
        return iCloudIntercomDeviceServiceDao.getUnitIdByRoomInfoId(roomId);
    }

    /**
     * <desc>
     * 通过设备的唯一标识查询设备所在地址
     * </desc>
     *
     * @param deviceUnique
     * @Author chengshican
     * @Date 2021-01-27 9:55
     * @Param deviceUnique 设备唯一标识符
     * @Return buildId 楼栋id   unitId  单元id
     * @Exception
     */
    @Override
    public  List<Map<String, String>> getUnitIdByDeviceUnique(String deviceUnique) {
        return iCloudIntercomDeviceServiceDao.getUnitIdByDeviceUnique(deviceUnique);
    }

    /**
     * <desc>
     * 通过设备的唯一标识查询设备所在地址
     * </desc>
     *
     * @param deviceUnique
     * @Author chengshican
     * @Date 2021-01-27 9:55
     * @Param deviceUnique 设备唯一标识符
     * @Return buildId 楼栋id   unitId  单元id
     * @Exception
     */
    @Override
    public  List<Map<String, String>> getUnitIdByEntranceDeviceUnique(String deviceUnique) {
        return iCloudIntercomDeviceServiceDao.getUnitIdByEntranceDeviceUnique(deviceUnique);
    }
    /**
     * <desc>
     * 根据地址获取电梯设备信息
     * </desc>
     *
     * @param address
     * @Author chengshican
     * @Date 2021-01-27 9:55
     * @Param buildId 楼栋id   unitId  单元id
     * @Return deviceUnique 电梯设备的唯一标识符    liftDoorType 正背门信息  （正背门 1正门 0背门）
     * @Exception
     */
    @Override
    public List<CloudElevatorVO> getElevatorLiftDoorTypeListByAddress(Map<String, String> address) {
        return iCloudIntercomDeviceServiceDao.getElevatorLiftDoorTypeListByAddress(address);
    }


    /**
     * <desc>
     *      获取云对讲黑名单
     * </desc>
     *
     * @param sn
     * @param page
     * @param pSize
     * @return
     * @author Jiaqi.X
     * @createDate 2019/10/14
     */
    public DeviceBlackListPageVO<BlackListVO> pullBlackList(String sn,String page,String pSize){
        String deviceUnique = StringHandlerUtil.getDeviceUniqueBySn(sn);
        String projectId = StringHandlerUtil.getProjectIdBySn(sn);
        DeviceBlackListPageVO<BlackListVO> pager = new DeviceBlackListPageVO<>();
        int currentPage = StringUtils.isNotBlank(page) ? Integer.valueOf(page) : 1;
        int pageSize = StringUtils.isNotBlank(pSize) ? Integer.valueOf(pSize) : 20;
        int startPage = (currentPage-1)*pageSize;
        int endPage = (currentPage-1)*pageSize+pageSize;
        int count = 1;
        int haveNext = 0;
        int currentCount = 0;
         Map<String,Object> address = iCloudIntercomDeviceServiceDao.getAddressByDeviceUnique(deviceUnique);
        List<BlackListVO> blackList = new ArrayList<>();
        Set<String> userIds = new HashSet<>();
        if(address != null) {
            String[] buildIds = StringHandlerUtil.splitString(StringHandlerUtil.getNullOrStringForObject(address.get("buildIds")));
            String[] unitIds = StringHandlerUtil.splitString(StringHandlerUtil.getNullOrStringForObject(address.get("unitIds")));
            if ((buildIds != null && buildIds.length > 0 ) && (unitIds != null && unitIds.length > 0)) {
                //地址用户
                List<UserBlackInfoVO> users = iCloudIntercomDeviceServiceDao.getUserBlackInfos(buildIds, unitIds,projectId);
                for (UserBlackInfoVO user : users) {
                    if (count >= startPage && count <= endPage) {
                        if (userIds.add(user.getUid() + user.getRoomNo())) {
                            if (user.getUsableCount() == null || user.getUsableCount() <= 0) {
                                BlackListVO blackListVO = new BlackListVO();
                                blackListVO.setUid(StringHandlerUtil.autlSupply(8, user.getUid(), "0"));
                                blackListVO.setType(1);
                                blackListVO.setStatus(1);
                                blackListVO.setBatch(Integer.valueOf(user.getBatch()));
                                blackListVO.setRoomNo(StringHandlerUtil.autlSupply(2, Integer.toHexString(Integer.valueOf(user.getRoomNo())), "0"));
                                blackList.add(blackListVO);
                                currentCount++;
                                count++;
                            }
                        }
                    } else {
                        haveNext = 1;
                    }
                }
            }
        }
        //临时权限黑名单
        List<UserBlackInfoVO> tempUsers = iCloudIntercomDeviceServiceDao.getTempBlackInfos(StringHandlerUtil.getProjectIdByDeviceUnique(deviceUnique),
                Integer.valueOf(StringHandlerUtil.getDeviceIdByDeviceUnique(deviceUnique)));
        for(UserBlackInfoVO user : tempUsers){
            if(count>=startPage && count<=endPage) {
                if(userIds.add(user.getUid()+user.getRoomNo())) {
                    if (user.getUsableCount() == null || user.getUsableCount() <= 0) {
                        BlackListVO blackListVO = new BlackListVO();
                        blackListVO.setUid(StringHandlerUtil.autlSupply(8, user.getUid(), "0"));
                        blackListVO.setType(1);
                        blackListVO.setStatus(1);
                        blackListVO.setBatch(Integer.valueOf(user.getBatch()));
                        blackListVO.setRoomNo(StringHandlerUtil.autlSupply(2, Integer.toHexString(Integer.valueOf(user.getRoomNo())), "0"));
                        blackList.add(blackListVO);
                        currentCount++;
                        count++;
                    }
                }
            }else{
                haveNext = 1;
            }
        }
        pager.setBlackListArr(blackList);
        pager.setTotal(count);
        pager.setPage(currentPage);
        pager.setCurrentTotal(currentCount);
        pager.setHaveNext(haveNext);
        return pager;
    }
}
